WCF and Proxies - Programmatic Client Configuration
(Page 2 of 6 )
Instead of relying on a config file, the client can programmatically construct address and binding objects matching the service endpoint and provide them to the proxy constructor. There is no need to provide the contract, since that was provided in the form of the generic type parameter of the proxy. To represent the address, the client needs to instantiate an EndpointAddress class, defined as:
public class EndpointAddress
{
public EndpointAddress(string uri);
//More members
}
Example 1-20 demonstrates this technique, showing the code equivalent to Example 1-16 targeting the service in Example 1-9.
Example 1-20. Programmatic client configuration
Binding wsBinding = new WSHttpBinding(); EndpointAddress endpointAddress = new
EndpointAddress("http://localhost:8000/MyService/");
MyContractClient proxy = new MyContractClient(wsBinding,endpointAddress);
proxy.MyMethod();
proxy.Close();
Similar to using a binding section in a config file, the client can programmatically configure the binding properties:
WSHttpBinding wsBinding = new WSHttpBinding();
wsBinding.SendTimeout = TimeSpan.FromMinutes(5);
wsBinding.TransactionFlow = true;
EndpointAddress endpointAddress = new
EndpointAddress("http://localhost:8000/MyService/");
MyContractClient proxy = new MyContractClient(wsBinding,endpointAddress);
proxy.MyMethod();
proxy.Close();
Again, note the use of the concrete subclass ofBindingin order to access binding-specific properties such as the transaction flow.
Programmatic Versus Administrative Configuration
The two techniques shown so far for configuring both the client and service complement each other. Administrative configuration gives you the option to change major aspects of the service and the client post-deployment, without even the need to rebuild or redeploy. The major downside of administrative configuration is that it is not type-safe, and configuration errors will only be discovered at runtime.
Programmatic configuration is useful when the configuration decision is either completely dynamic—when it is taken at runtime based on the current input or conditions—or when the decision is static and never changes, in which case you might as well hardcode it. For example, if you are interested in hosting in-proc calls only, you might as well hardcode the use of theNetNamedPipeBindingand its configuration. However, by and large, most clients and services do resort to using a config file.
Next: WCF Architecture >>
More Windows Scripting Articles
More By O'Reilly Media
|
This article is excerpted from chapter one of Programming WCF Services, written by Juval Lowry (O'Reilly, 2007; ISBN: 0596526997). Check it out today at your favorite bookstore. Buy this book now.
|
|