Instance management in WCF

Introduction: Instance management in WCF.

Instance Management: Many times we would like to control the way WCF service objects which are instantiated on WCF server. Sometimes, we would like to control how long the WCF instances should be residing on the server.

Why we need Instance Management

We need Instance Management because there are too much difference in applications for their needs of scalability, performance, throughput, transactions and queued calls.

There are 3 ways by which we can manage WCF service instance creation.

  • Per-Call
  • Per-Session
  • Single

Per-Call instance mode

When we configure WCF service as per call, new service instances are created for every method call you make via WCF proxy client.

• WCF client makes first method call (method call 1).
• New WCF service instance is created on the server for this method call.
• WCF service serves the request and sends response and the WCF instance is destroyed and given to garbage collector for clean up.

Per call instance mode is shown in figure below:

Per call instance mode

Per session instance mode
 
Many times we would like to maintain state between method calls or for a particular session. For this purpose, we will need to configure the service as per session. In per session, only one instance of WCF service object is created for a session interaction.

• Client creates the proxy of WCF service and makes method calls.
• One WCF service instance is created which serves the method response.
• Client makes one more method call in the same session.
• The same WCF service instance serves the method call.
• When client finishes his activity the WCF instance is destroyed and served to garbage collector for clean up.

Single instance mode
 
Many times we would like to create one global WCF instance for all WCF clients. To create one single instance of WCF service we need to configure the WCF service as ‘Single' instance mode.

• WCF client1  requests a method call on WCF service.
• WCF service instance is created and the request is served. WCF service instance is not destroyed the service instance is persisted to server other
   requests.
• Now let's say some other WCF client i.e. client2 requests a method call on WCF Service.
• Again, The same WCF instance which was created by WCF client1 is used to serve the request of WCF client2.
 

Single instance mode is shown in figure below:

Single instance mode