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:
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:
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.
Run the code and you can see the results.
Easy...!!! Isn't it. Happy coding...!!!