Showing posts with label ClientBase. Show all posts
Showing posts with label ClientBase. Show all posts

Sunday, November 27, 2011

Extending ClientBase to Create a WCF Service Proxy

I was trying to explore different ways of creating a proxy to use the service. I knew 3 ways to doing it
1.using SVCUtil.exe
2.using Add Service Reference
3.using ChannelFactory<T> and DuplexChannelFactory<T> classes
As and when I explored that we could also create a proxy by using a wonderful class ClientBase<T>
Here are the steps I followed to create a Proxy using ClientBase<T>
1.Created a Sample service and Hosted in IIS
2.Copy the Service Interface to Client Code
3.Extend the ClientBase<T>
4. Create the proxy in the client and use

1.The Service Interface is as follows
[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);


        // TODO: Add your service operations here
    }


The Implementation is as follows
  public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

    
    }


2. I copied the Service interface  to the Client Code
3. Extended the ClientBase<T> as Follow
    
    class ServiceClient:ClientBase<IService1>,IService1
    {

        public ServiceClient(BasicHttpBinding binding, EndpointAddress address
            ):base(binding,address)
        {

        }
        protected override IService1  CreateChannel()
{
        return base.CreateChannel();
}
   
public string  GetData(int value)
{
       return base.Channel.GetData(value); 
}
}
}


4.We can Invoke the custom handcoded proxy as follows
class Program
    {
        static void Main(string[] args)
        {
            ServiceClient client = new ServiceClient(new BasicHttpBinding(BasicHttpSecurityMode.None), new EndpointAddress("http://mycomputer:61468/Service1.svc"));
            Console.WriteLine(client.GetData(10));
            Console.ReadLine();
        }
    }