Search This Blog

2013/10/18

How to Create Proxy Class in WCF:



First create a console application, into that console app add the interface that is acting as contract for WCF service under consideration.
Make sure that it falls in same namespace as our console application. 

Here is sample Contract Interface

    [ServiceContract]
    public interface IMath
    {
        [OperationContract]
        double Add(double x, double y);

        [OperationContract]
        double Substract(double x, double y);

        [OperationContract]
        double Multiply(double x, double y);

        [OperationContract]
        double Device(double x, double y);
    }

Now add a class to console app say MathProxy.cs Here we need to create a proxy class for our wcf service so if wcf service changed we need to change only this class but not everywhere we used wcf service methods if no proxy class created at all
We are using ClientBase Class to create proxy class

class MathProxy : ClientBase<IMath>, IMath
    {
        public MathProxy(WSHttpBinding binding, EndpointAddress address): base(binding, address)
        {

        }

        protected override IMath CreateChannel()
        {
            return base.CreateChannel();
        }

        public double Add(double x, double y)
        {
            return base.Channel.Add(x, y);
        }

        public double Substract(double x, double y)
        {
            return base.Channel.Substract(x, y);
        }

        public double Multiply(double x, double y)
        {
            return base.Channel.Multiply(x, y);
        }

        public double Device(double x, double y)
        {
            return base.Channel.Device(x, y);
        }
    }

Make sure that binding has support in service in our case our wcf service support “WSHttpBinding

Now Using Proxy Class :
In our console application’s program.cs go to main function and change it as follows

static void Main(string[] args)
        {
            MathProxy proxy = new MathProxy(new WSHttpBinding(), new EndpointAddress("http://localhost:8090/MyService/Math"));
            Console.WriteLine( "10+  20 = " + proxy.Add(10, 20).ToString());
            Console.ReadLine();
        }
Before running this console application make sure that wcf service under consideration is running at hosting application may be iis, self-hosted or in new Window Activation services.

No comments:

Post a Comment