WCF Essentials—Working with Channels


Jump to: navigation, search
CSharp-Online.NET:Articles
.NET Articles

WCF Essentials

© 2007 O'Reilly Media

Working with Channels

You can use channels directly to invoke operations on the service without ever resorting to using a proxy class. The ChannelFactory<T> class (and its supporting types), shown in Example 1-21, enables you to create a proxy on the fly.

Example 1-21. TheChannelFactory<T> class
public class ContractDescription
{
   public Type ContractType
   {get;set;}
   //More members
}
public class ServiceEndpoint
{
   public ServiceEndpoint
     (ContractDescription contract,Binding binding,
      EndpointAddress address);
   public EndpointAddress Address
   {get;set;}
   public Binding Binding
   {get;set;}
   public ContractDescription Contract
   {get;}
   //More members
}
public abstract class ChannelFactory : ...
{
   public ServiceEndpoint Endpoint
   {get;}
   //More members
}
public class ChannelFactory<T> : ChannelFactory,...
{
   public ChannelFactory(ServiceEndpoint endpoint);
   public ChannelFactory(string configurationName);
   public ChannelFactory(Binding binding,
      EndpointAddress endpointAddress);
   public static T CreateChannel(Binding binding,
      EndpointAddress endpointAddress);
   public T CreateChannel( );
   //More Members
}

You need to provide the constructor of ChannelFactory<T> with the endpoint—either the endpoint name from the client config file, or the binding and address objects, or a ServiceEndpoint object. Next, use the CreateChannel( ) method to obtain a reference to the proxy and use its methods. Finally, close the proxy by either casting it to IDisposable and calling the Dispose( ) method or to ICommunicationObject and calling the Close( ) method:

ChannelFactory<IMyContract> factory = 
   new ChannelFactory<IMyContract>( );
 
IMyContract proxy1 = factory.CreateChannel( );
using(proxy1 as IDisposable)
{
   proxy1.MyMethod( );
}
 
IMyContract proxy2 = factory.CreateChannel( );
proxy2.MyMethod( );
ICommunicationObject channel = proxy2 as ICommunicationObject;
Debug.Assert(channel != null);
channel.Close( );

You can also use the shorthand static CreateChannel( ) method to create a proxy given a binding and an address, without directly constructing an instance of ChannelFactory<T>:

Binding binding = new NetTcpBinding( );
EndpointAddress address = 
   new EndpointAddress("net.tcp://localhost:8000");
IMyContract proxy = 
   ChannelFactory<IMyContract>.CreateChannel(binding,address);
 
using(proxy as IDisposable)
{
   proxy1.MyMethod( );
}


Previous_Page_.gif Next_Page_.gif


Personal tools