InstanceContextMode tells how the instanceContext object need maintain/handle/available for the incoming messages.
What is the Use of InstanceContextMode?
Basically it tell how the object create for the request/response must be handle across the service.
In our Business requirement let see what are all different type of requirement you may face
1) For some of you request you may need to maintain information for the each user and its scope of information is limited to each user (SESSION)
EX:- While a client request to service first time new instance will get created after that request come form same client will handle by the same instance until it gets disconnected/Expired.
2) Some time you need to maintain the information common to all user request to share the information across all the clients
EX: Update each share value to the requested users.
3) Some other request just you want to pass information to service, which may return the value back to client or may not based on your need.
Let see how we can implement it using WCF InstanceContextMode
There are 3 different type of InstanceContextMode
– For every request separate InstanceContext object gets created and destroyed after respond back to the client, just Request/Response pattern.
– Decorate [ServiceBehaviour(InstanceContextMode=InstanceContextMode.PerCall)] for the class that you want to include the InstanceContextMode.
– When first time request comes from the client new object will gets created, after that when ever subsequent call comes from the same client, the request are handle by the same instance object. This object will alive in service untill the client get disconnect or that instance object goes to ideal mode for some time. Default session expire time is 10 min.
– Decorate [ServiceBehaviour(InstanceContextMode=InstanceContextMode.PerSession)] for the class that you want to include the InstanceContextMode.
– This object is global for all the request/response. When ever new request are comes from the client it won;t create new instance because of that performance gets improved.
– Decorate [ServiceBehaviour(InstanceContextMode=InstanceContextMode.Single)] for the class that you want to include the InstanceContextMode.
You need to decorate corresponding servicebehaviour attribute in the class, else it will behave as request/response fromat and also based on how you create object in client side to call the service.
To download the sample code click here