Wednesday 1 August 2012

WCF : Session and Instance Management


1.    What are Sessions in WCF?
In WCF, there is always a service class instance that handles incoming service requests. These instances may already be there (at server when request arrives) or may be created as needed. In WCF, the concept of session is mainly to manage these service instances so that server can be utilized in an optimized way. At the server, there is one special class named InstanceContext that creates/loads service class instance and dispatches requests to it.
When some request arrives, it is routed to service instance via instance context. Suppose there is a hit of thousand requests, then service will have to create thousand instance contexts (which in turn will create thousand service instances) to handle these requests. If requests are served in this way, then service is called PERCALL service as each request is served by a new instance context and service instance object (call them as service objects onwards). Consider there is a client that made 100 requests. If service identifies this client and always serves it by a dedicated service object, then this type of service will be known as PERSESSION service as it recognizes the client and serves it by a single instance of service object. On the other hand, if all the requests irrespective of client are served by a single instance of service objects, then the service will be known as SINGLETON service.

2.    What is instance management in WCF?
ü  Instance management refers to the way a service handles a request from a client. Instance management is set of techniques WCF uses to bind client request to service instance, governing which service instance handles which client request.
ü  It is necessary because application will differ in their need for scalability, performance, durability, transaction and queued calls.
3.    What are the instance modes in WCF?
ü  Basically there are three instance modes in WCF:
·         Per-Call instance mode
·         Per-Session instance mode
·         Singleton Instance Mode

4.    How do you implement instance modes in a service?
ü  Instance mode can be configured using ServiceBehavior attribute. This can be specified at implementing the service contract as shown below.
  [ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        int MyMethod();
    }
  
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class MyService:IMyService
    {
 
        public int MyMethod()
        {
            //Do something
        }       
    }
5.    Explain 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.

ü  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. 

6.    Explain Per-Session Service
ü  When WCF service is configured for Per-Session instance mode, logical session between client and service will be maintained. When the client creates new proxy to particular service instance, a dedicated service instance will be provided to the client. It is independent of all other instance.

ü     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 PerSession 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 will be incremented and return the value to the client.
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
    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-Session");
            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();
        }
ü  All request to service return incremented value (1, 2, 3, 4), because we configured the instance mode to Per-Session. Service instance will be created once the proxy is created at client side. So each time request is made to the service, static variable is incremented.
7.    What are the advantages and disadvantages of using PerSession instancing mode in WCF?

ü  A new service object gets created for each client/proxy.
ü  The following are the advantages and Disadvantages of PerSession instance mode.
Advantages:
State maintained by service instance
Disadvantages:
Less throughput, greater memory consumption
Concurrency issues for multithreaded clients
  
8.    Explain 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.


ü  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. 
9.    What are the advantages and disadvantages of using Single, Instancing mode in WCF?
   
ü  In a single instancing mode, a single service object is created for all calls from all clients and sessions
ü  This type of wcf service is also called as singleton service.
ü  The following are the advantages and Disadvantages of Single instance mode.
Advantages:
State maintained by service instance
Disadvantages:
Least throughput
Potentially greater memory consumption
Concurrency issues


10. Explain Instance Deactivation.
ü  Session actually correlated the client message not to the instance, but to the context that host it. When session starts, context is created and when it closes, context is terminated. WCF provides the option of separating the two lifetimes and deactivating the instance separately from its context.
11. What are the various properties and attributes needed for instance deactivation?
ü  ReleaseInstanceMode property of the OberationalBehavior attribute used to control the instance in relation to the method call.
[ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
   [OperationBehavior(ReleaseInstanceMode=ReleaseInstanceMode.BeforeCall]
    public int Add(int num1, int num2)
    {
        return num1 + num2;            
    }

12. What are the various instance deactivation techniques available.
·         RealeaseInstanceMode.None
·         RealeaseInstanceMode.BeforeCall
·         RealeaseInstanceMode.AfterCall
·         RealeaseInstanceMode.BeforeAndAfterCall
13.Explain   RelaeseInstanceMode.None
ü  This property means that it will not affect the instance lifetime. By default ReleaseInstanceMode property is set to 'None'.


14.Explain  RealeaseInstanceMode.BeforeCall
ü  This property means that it will create new instance before a call is made to the operation.
ü  If the instance is already exist,WCF deactivates the instance and calls Dispose() before the call is done. This is designed to optimize a method such as Create()

15.Explain RealeaseInstanceMode.AfterCall
ü  This property means that it will deactivate the instance after call is made to the method.
ü  This is designed to optimize a method such a Cleanup()

16.Explain  RealeaseInstanceMode.BeforeAndAfterCall
ü  This is means that it will create new instance of object before a call and deactivates the instance after call. This has combined effect of using ReleaseInstanceMode.BeforeCall and ReleaseInstanceMode.AfterCall

17.Can you explicitly deactivate service instance?
Yes, You can also explicitly deactivate instance using InstanceContext object as shown below.
   [ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        void MyMethod();
    }
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class MyService:IMyService
    {
 
        public void MyMethod()
        {
           //Do something
           OperationContext.Current.InstanceContext.ReleaseServiceInstance();
            
        }       
    }
18.  What are the general guidelines for choosing an instancing mode?
ü  In general, for scalability and throughput, prefer to use PerCall services where ever possible.
ü  Use PerSession services only when necessary, but keep in mind the overhead of sessions and session timeouts. Try to avoid singletons almost always.
ü  Singleton services, could be useful on client machines for shared functionality.
ü  These are only general guidelines, and your selection depends on what you are trying to achieve

5 comments:

  1. I always enjoy reading quality articles by an individual who is obviously knowledgeable on their chosen subject. Ill be watching this post with much interest. Keep up the great work, I will be back
    Selenium training in Chennai

    Selenium training in Bangalore

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.keep it up!!

    android training in chennai

    android online training in chennai

    android training in bangalore

    android training in hyderabad

    android Training in coimbatore

    android training

    android online training

    ReplyDelete