Instance management using InstanceContextMode property in WCF

This article describes you about how to manage WCF instances using InstanceContextMode. It gives detail description about PerCall, PerSession, Single modes of instancing.

Instance management is service side implementation and it has no effect of client side configuration. InstanceContextMode property is used with service behavior and applies to all service endpoints and it specifies how service object creation happens on service side. Instancing in correct way is important as it affects scalability, throughput, transactions, queued calls.


There are three choices available for the InstanceContextMode property as PerCall, PerSession and Single. Those choices are described below.


InstanceContextMode = InstanceContextMode.PerCall

When we configure WCF service as PerCall each client request will get its own copy of service instance and implementation objects. When you are using binding with no reliable session or configure your bindings for reliable session as false, PerCall is the default value for InstanceContextMode.Property.

PerCall services are the best when you require highly scalable WCF services as these services are stateless and does not maintain any state between calls. However if you still wants to maintain state while using PerCall InstanceContextMode you can store required data in database or AppFabric caching and restore it on subsequent calls.

Also PerCall Services are considered to be best when the amount work for each client request is small and it does not need any background process once instance got disposed.

PerCall instantiation happens in below sequence.

  • Client makes a call to WCF service Operation.
  • WCF Service create new dedicated instance for this particular operation.
  • WCF Service instance serve the request and if required send the response to client.
  • WCF service instance gets destroyed and send it for garbage collection.
  • If same client or any other client make request for service operation, new dedicated instance will be created to service new request.

Below picture describes how PerCall instantiation happens

WCF InstanceContextMode.PerCall


Implementation of PerCall WCF Service

        
    namespace Northwind.ServiceContracts
    {
        [ServiceContract(Name = "ProductService", 
            Namespace = "http://northwind.com/productservice" )]
        public interface IProductService
        {
            [OperationContract] 
            string GetProductName(int productID);

            [OperationContract]
            int GetProductQty(int productID);
        }
    }


    namespace Northwind.ProductServices
    {
        [ServiceBehavior(Name = "ProductService",
             Namespace = "http://northwind.com/productservice",
            InstanceContextMode=InstanceContextMode.PerCall)] 
        public  class ProductService : IProductService 
        {
            public string GetProductName(int productID)
            {
                return "Aniseed Syrup";
            }

            public int GetProductQty(int productID)
            {
                return 13;
            }
        }
    }
            
    

Drawbacks of InstanceContextMode.PerCall: it can not handle resources that are expensive to allocate or available in very limited numbers for client. For example a file manager service which opens a file and updates its content. If first instance is in process for updating the file, it will hold the file until operation completes and other instances will be unable to access this file.

Check how per call service instance works in wcf for more detail description and implementation of PerCall behavior.


InstanceContextMode=InstanceContextMode.PerSession

When we configure service as PerSession, each WCF client proxy will get its own instance of wcf service and implementation objects. If your service is configured to use bindings with reliable session, security then PerSession is default value for InstanceContextMode property.

Windows Communication Foundation is able maintain a exclusive session between a client and a particular service instance. When the client creates a new proxy to a service configured for maintaining session, it gets new independent service instance. This instance is dedicated to processing the requests that come from same client proxy. Any subsequent calls from same client proxy will be considered as part of same session.

Instance will remain in service memory till the client closes proxy. Each client proxy uniquely binds particular service instance means each client proxy gets unique identifier and this identifier will be used by service host to redirect request to appropriate service instance. Note that the client session has one service instance per proxy. If the client creates another proxy to the same or a different endpoint, that second proxy will be associated with a new instance and session.

PerSession instantiation happens in below sequence.

  • Client makes a call to WCF service Operation configured for maintaining sessions.
  • WCF Service creates new dedicated instance for this operation.
  • WCF Service instance serves the request and if required send the response to client.
  • If same proxy requests for same or other operation, request is served by same instance created for previous operation call.
  • If client close proxy WCF service instance gets destroyed and send it for garbage collection.
  • If any other client proxy make new request for service operation, new dedicated instance will be created to serivce new request.

Below picture shows how PerSession instantiation happens

WCF InstanceContextMode.PerSession

Implementation of PerSession WCF Service

        
    namespace Northwind.ServiceContracts
    {
        [ServiceContract(Name = "CustomerCartService",
            Namespace = "http://northwind.com/CustomerCartService",
            SessionMode=SessionMode.Required)]
        public interface ICustomerCartService
        {
            [OperationContract]
            bool AddProductsToCart(int productID);
        }
    }

    namespace Northwind.CustomerCartServices
    {
        [ServiceBehavior(Name = "CategoryService",
             Namespace = "http://northwind.com/CustomerCartService",
             InstanceContextMode=InstanceContextMode.PerSession )] 
        public class CustomerCartService : ICustomerCartService
        {
            public bool AddProductsToCart(int productID);
            {
                // code for adding product to customer cart.
                return true;
            }
        }
    }
    

Drawbacks of InstanceContextMode.PerSession: you can not expose any endpoint with binding which does not support reliable sessions. If you do not use reliable session it throws InvalidOperationException.

Check how per session service instance works in wcf for more detail description and implementation of PerSession behavior.


InstanceContextMode=InstanceContextMode.Single

Single mode creates only one instance and handle each and every request. All clients of Singleton service get connected to same instance independent of other clients. Singleton service instance is created when host is created, lives forever till the service host shutdown.

Singleton mode does not require any session information to communicate with service. There is no constraint on which binding to use. If the service exposed endpoint with session enabled then client must provide session details. Session identifier maintained in client proxy until client destroyed the proxy.

Singleton services are best used when services deals with only one resource like updating products through flat files, provide global cache, log files as it reduces need of creating expensive references to those objects.

You can create singleton instance through constructor, it may involve performing initialization of resources like connecting and open file, connecting to database, update cache. This will make sure all required resources are initialized, allocated and ready to use by each request.

Singleton instantiation created like

  • WCF client 1 requests a method call for WCF service.
  • A WCF service instance is created, if required resources are not available then initialization, allocation for those resources are done and will be keept in memory for subsequent requests. The request is served for client1. The WCF service instance is not destroyed, the service instance is persisted to server other requests.
  • Now let’s say some other WCF client or same client or same proxy, requests a method call. The same WCF instance which was created for WCF client 1 is used to serve the request for WCF client 2. In other words, only one global WCF service instance is created to serve all client requests.

Below picture describes how Single instantiation works.

WCF InstanceContextMode.Single


Implementation of Singleton WCF Service

        
    namespace Northwind.ServiceContracts
    {
        [ServiceContract(Name = "FileManager",
             Namespace = "http://northwind.com/FileManager" )]
        public interface IFileManager
        {
            [OperationContract] 
            bool updatepProducts(string productDetails);        
        }
    }

    namespace Northwind.FileManagers
    {
        [ServiceBehavior(Name = "FileManager",
             Namespace = "http://northwind.com/FileManager",
            InstanceContextMode=InstanceContextMode.Single )] 
        public  class FileManagerService : IFileManager 
        {
            public bool updatepProducts(string productDetails)        
            {
                //process string productDetails and update flat file 
                return true;
            }
        }
    }
    

Drawbacks of InstanceContextMode.Single: scalability is the big issue with singleton services. The objects created by singleton instance needs to be in service memory for all time and for each request.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com