Tuesday, August 11, 2015

WCF Proxy generation using ClientBase

This is the final wcf proxy generation technique that we will discuss in our series about wcf services. It will be on how we can generate the wcf proxy using the ClientBase class. We will be using the same service which we created in our previous discussions. If you have missed the other articles, 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'
  5. WCF Proxy generation using 'Channel Factory'

before we start, we exclude the Service client that we generated in the previous discussion and add a new class named ClientBaseProxy

Next, we inherit the ClientBase<T> class where the type T is our service interface type i.e. IService1. This class will basically help us to connect with the service and call it's methods. We also implement the service interface IService1. 

   namespace WCFClient
     public class ClientBaseProxy : ClientBase<IService1>, IService1
        public Int32 GetSum(Int32 a, Int32 b)
            return base.Channel.GetSum(a, b);

In this implementation, we use the  base.Channel method from ClientBase to call the GetSum method in IService1. This becomes possible as we have declared the ClientBase to be of type IService1. So we are able to access it's methods. 

Next we add the binding and the endpoint settings in the client config file. We had removed these settings when we used the proxy generated through the SvcUtil.exe tool. So our config file looks like following:

<?xml version="1.0" encoding="utf-8" ?>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
        <binding name="BasicHttpBinding_IService1" />
      <endpoint address="http://localhost:13490/Service1.svc" binding="basicHttpBinding"
          bindingConfiguration="BasicHttpBinding_IService1" contract="ISampleServiceInterface.IService1"
          name="BasicHttpBinding_IService1" />

So now simply we create an instance of the proxy class and call it's methods, which in-turn, call the actual service method using the base.Channel. See the code below:

    ClientBaseProxy _proxy = new ClientBaseProxy();
    Console.WriteLine("Sum is: " +  _proxy.GetSum(12, 2));

Simply run the application and see the results. 

Easy to create isn't it. Happy coding...!!!

No comments:

Post a Comment