Saturday 28 January 2012

Singleton Service

When WCF service is configured for Singleton instance mode, all clients are independently connected to the same single instance. This singleton instance will be created when service is hosted and, it is disposed when host shuts down.
Following diagram represent the process of handling the request from client using Singleton instance mode.
 


 
Let as understand the Singleton 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 Single 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.Single)]
    public class MyService:IMyService
    {
        static int m_Counter = 0;

        public int MyMethod()
        {
            m_Counter++;
            return m_Counter;
        }       
    }
Step 3: Client side, create the two proxies for the service and made a multiple call to MyMethod.
static void Main(string[] args)
        {
Console.WriteLine("Service Instance mode: Singleton");
            Console.WriteLine("Client 1 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("Client 2 making call to service...");
            //Creating new proxy to act as new client
            MyCalculatorServiceProxy.MyServiceProxy proxy2 =
             new MyCalculatorServiceProxy.MyServiceProxy();
            Console.WriteLine("Counter: " + proxy2.MyMethod());
            Console.WriteLine("Counter: " + proxy2.MyMethod());
            Console.ReadLine();
  }
  
When two proxy class made a request to service, single instance at service will handle it and it return incremented value (1, 2, 3, 4), because instance mode is configured to 'Single'. Service instance is created when it is hosted. So this instance will remain till host is shutdown. Output is shown below.
Fig: SingletonOutput.

No comments:

Post a Comment