Tuesday, August 4, 2015

WCF Proxy generation - using ChannelFactory

Next in our series about wcf service, we will now discuss how we can generate the wcf proxy using the ChannelFactory class. If you have missed the series, then here are the links for the series:

  1. About the A.B.C. of WCF Service
  2. Types of Contracts in WCF
  3. WCF Proxy generation using 'Add reference'
  4. WCF Proxy generation using 'SvcUtil.exe' 
So let's start with it. As per MSDN, ChannelFactory class is:

A factory that creates channels of different types that are used by clients to send messages to variously configured service endpoints.
This approach has the big advantage that we need not add the Service Reference to our client application, like we did in our very first discussion article. But this approach requires one very important thing, which is sharing of the ServiceContract between the client and service so that the channel can be created, based on the contract (which the service provides), between the client and service. So this makes it very important to use the concept of interfaces which can be shared between the two in a de-coupled manner. So let's start with the discussion.
We will use the same service which we used in our previous discussions. But make sure that we have removed the service reference from the project. Also we remove all the binding and endpoint configuration from the config file. We will be setting these values in our C# code.
But before we start, we move the service interface i.e. IService1 to separate project. The reason, as we discussed above, we need to have the service contract to be available in both client and service itself and adding the reference to the service project does not makes any sense. So, we add a new class type project, move the interface IService1 to this project and add it's reference to both service and client projects. So our project structure changes to:
WCF Proxy using ChannelFactory
Next, we write the code to create binding to be used, the endpoint to be used and create a ChannelFactory<T> instance type, where T is of type IService1. From this channel factory created, we get the channel of type IService1 and use this to invoke the service method  
 static void Main(string[] args)
            BasicHttpBinding _basicHttpBinding = new BasicHttpBinding();
            EndpointAddress _endpoint = new EndpointAddress("http://localhost:9999/Service1.svc");

            ChannelFactory<IService1> _channelFactory = new ChannelFactory<IService1>(_basicHttpBinding, _endpoint);
            IService1 _channel = _channelFactory.CreateChannel();

            //Call the service operation
            Console.WriteLine("Sum is: " + _channel.GetSum(13, 5));

            //Close the channel Factory



Run the code and you can see the results.
WCF Proxy using ChannelFactory
Easy...!!! Isn't it. Happy coding...!!!

No comments:

Post a Comment