Instance management basically defines the binding of service instance to a request received from a client. In case of WCF, the following three techniques for service instantiation are available:
PerCall
PerSession
Single
As we know that application requirements vary from one to another with respect to scalability, durability, performance, transactions, etc., so in order to meet respective needs of the application, we choose between different WCF service instance modes.
"PerSession
" is the default instance mode for WCF Service. In order to use any specific techniques mentioned above, we need to configure serviceBehavior
attribute for a service as follows:
[ServiceContract()] public interface IInstanceManagDemoService
{ [OperationContract] string Method1(); }
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class InstanceManagDemoService : IInstanceManagDemoService
{ public string Method1() {
PerCall
In case of PerCall
Instance mode, a new instance is created against each request coming from client and later disposed off when response is sent back from service as shown in the following diagram:
The above diagram shows that all requests coming from one or more clients are served by separate instance on server. The key points about this approach are follows:
- We will prefer to use this approach when we don't need to maintain state between requests.
- Scalability is a major concern and service holds expensive resources like communication ports, files or database connections, etc.
PerSession
For PerSession
Instance mode, a new instance is maintained on server for one session. For separate session, another instance is created that serves the request. Normally, we use this technique when we need to maintain session between multiple requests.
The above diagram shows that for all requests from "WCF Client 1" are served by "Service Instance 1". Same is the case for client 2 and client 3 respectively. In this technique, the service instance is disposed of when a particular client completes all its method calls to perform a specific functionality.
The key points about this approach are as follows:
- Approach is preferable when we need to maintain state.
- Scalability is a concern but not the biggest concern.
Single
In case of Single/Singleton Instance mode, only one instance is created to serve all the requests coming from all clients.
In this technique, service instance is not disposed of and it stays on server to serve all incoming requests.
The key points about this approach are as follows:
- We want to share global data using service.
- Scalability is not a concern at all.
WCF Service Tutorials
CodeProject