Saturday 28 January 2012

Per-Call Service

When WCF service is configured for Per-Call instance mode, Service instance will be created for each client request. This Service instance will be disposed after response is sent back to client.




Following diagram represent the process of handling the request from client using Per-Call instance mode.
Let as understand the per-call instance mode using example.
Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerCall as show below.
    [ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        int MyMethod();
    }
Step 2: In this implementation of MyMethod operation, increment the static variable(m_Counter). Each time while making call to the service, m_Counter variable is incremented and return the value to the client.
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
    public class MyService:IMyService
    {
        static int m_Counter = 0;

        public int MyMethod()
        {
            m_Counter++;
            return m_Counter;
        }       
    }
 
Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time.
        static void Main(string[] args)
        {
            Console.WriteLine("Service Instance mode: Per-Call");
            Console.WriteLine("Client  making call to service...");
            //Creating the proxy on client side
            MyCalculatorServiceProxy.MyServiceProxy proxy =
             new MyCalculatorServiceProxy.MyServiceProxy();
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.ReadLine();
}
Surprisingly, all requests to service return '1', because we configured the Instance mode to Per-Call. Service instance will created for each request and value of static variable will be set to one. While return back, service instance will be disposed. Output is shown below.
Fig: PercallOutput.

No comments:

Post a Comment