Click here to Skip to main content
Click here to Skip to main content

3 ways to do WCF instance management (Per call, Per session and Single)

By , 8 Jul 2010
Rate this:
Please Sign up or sign in to vote.
This is an old version of the currently published article.

3 ways to do WCF instance management (Per call, Per session and Single)

 

Introduction
WCF service object instancing basics
Per Call instance mode
How to implement WCF per call instancing?
Per session Instance mode
How to implement per session Instancing?
Single Instance mode
How to implement Single Instance mode?
When should you use per call, per session and single mode?
Per call
Per session
Single
References
Source code
 


 

Introduction
 

Many times we would like to control the way WCF service objects are instantiated on WCF server. You would like to control how long the WCF instances should be residing on the server.


WCF framework has provided 3 ways by which we can control the WCF instance creation. In this article we will first try to understand those 3 ways of WCF service instance control with simple code samples of how to achieve them. Finally we will compare when to use under what situations.


This is a small Ebook for all my .NET friends which covers topics like WCF,WPF,WWF,Ajax,Core .NET,SQL etc you can download the same from here   or else you can catch me on my daily free training @ from here

WCF service object instancing basics
 

In a normal WCF request and response communication following sequence of actions takes place:-
• WCF client makes a request to WCF service object.
• WCF service object is instantiated.
• WCF service instance serves the request and sends the response to the WCF client.
Following is the pictorial representation of how WCF request and response work.
 

Following are different ways by which you would like to create WCF instances:-
• You would like to create new WCF service instance on every WCF client method call.
• Only one WCF service instance should be created for every WCF client session.
• Only one global WCF service instance should be created for all WCF clients.
To meet the above scenarios WCF has provided 3 ways by which you can control WCF service instances:-
• Per Call
• Per session
• Single instance
 

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. Below image shows the same in a pictorial format:-

• 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.
• Now let’s say WCF client makes a second method call, again a new instance is created, request is served and the WCF instance is destroyed.

In other words for every WCF client method call one WCF service instance is created and destroyed once the request is served.
 

How to implement WCF per call instancing?
 

In order to specify instancing mode we need to provide ‘InstanceContextMode’ value in the ‘ServiceBehavior’ attribute as shown below. This attribute we need to specify on the ‘Service’ class. In the below code snippet we have specified ‘intCounter’ as a class level variable as shown below and the class counter is incremented by one when method ‘Increment’ is called.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Percall)] 
public class Service : IService
{
private int intCounter;

public int Increment()
{
intCounter++
return intCounter;
}
}

 

At the client we have consumed the WCF client and we have called ‘Increment’ method twice.

ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 
MessageBox.Show(obj.Increment().ToString());
MessageBox.Show(obj.Increment().ToString());

 

Even though we have called the ‘Increment’ method twice we get value ‘1’. In other words the WCF service instance is created for every method call made to the WCF service instance so the value will always be one.
 

.

Per session Instance mode
 

Many times we would like to maintain state between method calls or for a particular session. For those kind of scenarios 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. Below figure explains the same in a pictorial format.

• 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.
 

How to implement per session Instancing?
 

To configure service as per session we need to configure ‘ServiceBehavior’ attribute with ‘PerSession’ value in the ‘InstanceContextMode’ object.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
public class Service : IService
{
private int intCounter;
public int Increment()
{
intCounter++
return intCounter;
}}

 

At the client side when we run the below client code. You should see the value as ‘2’ after the final client code is executed. We have called the method twice so the value will be seen as two.

ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 
MessageBox.Show(obj.Increment().ToString());
MessageBox.Show(obj.Increment().ToString());

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. Below is a simple pictorial notation of how single instance mode will operate:-

• WCF client 1 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. client 2 requests a method call.
• The same WCF instance which was created by WCF client 1 is used to serve the request of WCF client 2. In other words only one global WCF server service instance is created to serve all client requests.
 

How to implement Single Instance mode?
 

In order to create a single instance of WCF service we need to specify the ‘InstanceContextMode’ as ‘Single’.
 

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
public class Service : IService
{
}

If you call the WCF from different client you will see the counter keep incrementing. The counter has become a global variable.
 

When should you use per call, per session and single mode?
 

Per call


• You want a stateless services
• Your service hold intensive resources like connection object and huge memory objects.
• Scalability is a prime requirement. You would like to have scale out architecture.
• Your WCF functions are called in a single threaded model.
 

Per session


• You want to maintain states between WCF calls.
• You want ok with a Scale up architecture.
• Light resource references
 

Single


• You want share global data through your WCF service.
• Scalability is not a concern.
 

References
 

MSDN link for WCF instances http://msdn.microsoft.com/en-us/library/ms733040.aspx 
Do not miss this post which covers end to end about WCF sessions http://codeidol.com/csharp/wcf/Instance-Management/ 
Great blog by Rick rain on WCF instancing http://blogs.msdn.com/b/rickrain/archive/2009/06/15/wcf-instancing-concurrency-and-throttling-part-1.aspx
 

Source code
 

You can download source code for this tutorial from here
 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shivprasad koirala
Architect http://www.questpond.com
India India

I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos ,
writing books and corporate trainings. Do visit my site for 
.NET, C# , design pattern , WCF , Silverlight
, LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server  training 
and Interview questions and answers


Comments and Discussions


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
Questioninstance management PinmemberMember 1028374125-Feb-14 4:50 
Questionper session and single modes are not working.. but you have give good explanation. PinmemberMember 1006189521-Jan-14 2:07 
QuestionVery Good Article Pinmemberpuja111913-Nov-13 15:55 
QuestionFor PerSession to increment properly.... PinmemberMember 966905918-Oct-13 10:25 
GeneralMy vote of 5 PinmemberHasan Habib Surzo11-Sep-13 6:50 
QuestionMy Vote is 5 Pinmemberais073-Sep-13 1:57 
GeneralMy vote of 5 Pinmemberrwg21-Aug-13 4:39 
QuestionExcelent !! Pinmemberjuanchavezlive7-Aug-13 13:00 
GeneralMy vote of 5 PinmemberDane Balia2-Jul-13 1:40 
QuestionPerfect Pinmembermirko.boggian27-Jun-13 6:30 
QuestionThank you! Pinmemberdeise_3010-Jun-13 10:38 
GeneralMy vote of 5 PinmemberMohamed hammad10-Jun-13 9:59 
QuestionSo nicely explained and simply put! Pinmemberaxnst110-May-13 3:34 
Questioncommunication with multiple windows service hosted wcf services Pinmembervaishali thaker20-Apr-13 2:10 
QuestionPoor article PinmemberMember 451897613-Apr-13 17:40 
GeneralMy vote of 2 PinmemberMember 451897613-Apr-13 17:38 
GeneralMy vote of 5 Pinmemberbabu saravanan11-Apr-13 18:29 
GeneralMy vote of 5 PinmemberPiyushSinghi9-Apr-13 17:54 
GeneralMy vote of 4 PinmemberMorteza Azizi24-Mar-13 1:19 
QuestionCan I Implement this in WCF to mobile applications PinmemberMathewPV20-Mar-13 1:08 
AnswerRe: Can I Implement this in WCF to mobile applications PinmemberJaydeep Jadav30-May-13 3:54 
GeneralRe: Can I Implement this in WCF to mobile applications PinmemberMathewPV23-Jul-13 18:27 
GeneralRe: Can I Implement this in WCF to mobile applications PinmemberJaydeep Jadav23-Jul-13 20:12 
GeneralRe: Can I Implement this in WCF to mobile applications PinmemberJaydeep Jadav23-Jul-13 20:13 
QuestionVery usefull PinmemberChittananda13-Mar-13 21:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 8 Jul 2010
Article Copyright 2010 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid