3 Techniques For Instance Management in WCF

Instance management basically defines the binding of a service instance to a request received from a client. In the case of WCF, the following three techniques for service instantiation are available:

  • PerCall
  • PerSession
  • Single

As we know, application requirements variy with respect to scalability, durability, performance, transactions and so on, so in order to meet the respective needs of the application, we choose among various 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 the 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()
    {
        //method details here.....
    }
}

PerCall

In the case of PerCall Instance mode, a new instance is created against each request coming from a client and later disposed off when the response is sent back from the service as shown in the following diagram.

WCF1.jpg

The above diagram shows that all requests coming from one or more clients are served by separate instances on the server.

Key points about this approach are:

  • We will prefer to use this approach when we don't need to maintain state between requests.
  • Scalability is a major concern and the service holds expensive resources like communication ports, files or database connections and so on.

PerSession

For the PerSession Instance mode, a new instance is maintained on the server for one session. For separate sessions, another instance is created that serves the request. Normally, we use this technique when we need to maintain a session among multiple requests.

WCF2.jpg

The above diagram shows that all requests from "WCF Client 1" are served by "Service Instance 1". The same is the case for client 2 and client 3 respectively. In this technique, the service instance is disposed off when a specific client completes all its method calls to perform a specific functionality.

Key points about this approach are:

  • The approach is preferable when we need to maintain state.
  • Scalability is a concern but not the biggest concern.

Single

In the case of Single/Singleton Instance mode, only one instance is created to serve all the requests coming from all clients.

WCF3.jpg

In this technique, the service instance is not disposed of and it stays on the server to serve all incoming requests.

Key points about this approach are:

  • We want to share global data using service.
  • Scalability is not a concern at all.

Other relevant articles on C-SharpCorner are:

Up Next
    Ebook Download
    View all
    Learn
    View all