Click here to Skip to main content
11,636,300 members (76,114 online)
Click here to Skip to main content

Tagged as

Three ways to do WCF instance management

, 8 Jun 2010 CPOL 308.1K 6.5K 266
Rate this:
Please Sign up or sign in to vote.
Three ways to do WCF instance management (Per call, Per session, and Single).

Table of contents

Introduction

Very often we would like to control the way WCF service objects are instantiated on a WCF server. You would want to control how long the WCF instances should be residing on the server.

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

There is a small ebook for all my .NET friends which covers topics like WCF, WPF, WWF, AJAX, Core .NET, SQL, etc., which you can download from here or you can catch me on my daily free training from here.

WCF service object instancing basics

In normal WCF request and response communication, the following sequence of actions takes place:

  • WCF client makes a request to a WCF service object.
  • WCF service object is instantiated.
  • WCF service instance serves the request and sends the response to the WCF client.

Following is a pictorial representation of how WCF requests and responses work.

Following are different ways by which you can create WCF instances:

  • Create a 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 three ways by which you can control WCF service instances:

  • Per call
  • Per session
  • Single instance

Per call instance mode

When we configure a WCF service as per call, new service instances are created for every method call you make via a WCF proxy client. The image below shows this in a pictorial format:

  • The WCF client makes the first method call (method call 1).
  • A new WCF service instance is created on the server for this method call.
  • The WCF service serves the request and sends the response and the WCF instance is destroyed and given to the garbage collector for clean up.
  • Now let’s say the WCF client makes a second method call, a new instance is created, the request is served, and the WCF instance is destroyed.

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

How to implement WCF per call instancing

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

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

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

At the client, we consume the WCF client and we call the 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 the 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

Very often we need to maintain state between method calls or for a particular session. For those kinds of scenarios, we will need to configure the service per session. In per session, only one instance of a WCF service object is created for a session interaction. The figure below explains this in pictorial format.

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

How to implement per session instancing

To configure service as per session, we need to configure the ServiceBehavior attribute with a 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 ‘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

Often we would like to create one global WCF instance for all WCF clients. To create a single instance of a WCF service, we need to configure the WCF service as Single instance mode. Below is a simple pictorial notation of how the single instance mode will operate:

  • WCF client 1 requests a method call on the WCF service.
  • A WCF service instance is created and the request is served. The WCF service instance is not destroyed, the service instance is persisted to server other requests.
  • Now let’s say some other WCF client, e.g., client 2, requests a method call.
  • The same WCF instance which was created by WCF client 1 is used to serve the request for 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 a WCF service, we need to specify InstanceContextMode as Single.

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

If you call the WCF service from a different client, you will see the counter incrementing. The counter becomes a global variable.

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

Per call

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

Per session

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

Single

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

References

Source code

You can download the 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)

Share

About the Author

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

I am an ex-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


You may also be interested in...

Comments and Discussions

 
GeneralQuery regarding InstanceContextMode Pin
Chayan Floyd Kar9-Jun-15 4:59
memberChayan Floyd Kar9-Jun-15 4:59 
GeneralStructured, Well explained, and I am not left hanging. Pin
stixoffire27-May-15 3:58
memberstixoffire27-May-15 3:58 
GeneralMy vote of 5 Pin
Seyyed Hossein Hasan Pour7-Feb-15 22:55
memberSeyyed Hossein Hasan Pour7-Feb-15 22:55 
Questionwow 5 from me Pin
saxenaabhi619-Jan-15 12:54
membersaxenaabhi619-Jan-15 12:54 
QuestionSuper Pin
fmanrique1911-Dec-14 8:57
memberfmanrique1911-Dec-14 8:57 
GeneralMy vote of 3 Pin
luis r carrizo8-Aug-14 12:47
memberluis r carrizo8-Aug-14 12:47 
GeneralCode throwing error Pin
Member 1062927427-Jul-14 21:34
memberMember 1062927427-Jul-14 21:34 
QuestionWhat instance Management technique should I use for Implementing Queue. Pin
pravin.ovhal1-Jul-14 21:10
memberpravin.ovhal1-Jul-14 21:10 
QuestionHow many instances are created in the per call mechanism Pin
pravin.ovhal13-Jun-14 0:59
memberpravin.ovhal13-Jun-14 0:59 
QuestionGood gob Pin
didiman29-May-14 16:05
memberdidiman29-May-14 16:05 
GeneralMy vote of 5 Pin
yytg25-May-14 23:15
memberyytg25-May-14 23:15 
Questioninstance management Pin
Member 1028374125-Feb-14 4:50
memberMember 1028374125-Feb-14 4:50 
Questionper session and single modes are not working.. but you have give good explanation. Pin
Member 1006189521-Jan-14 2:07
memberMember 1006189521-Jan-14 2:07 
QuestionVery Good Article Pin
puja111913-Nov-13 15:55
memberpuja111913-Nov-13 15:55 
QuestionFor PerSession to increment properly.... Pin
Member 966905918-Oct-13 10:25
memberMember 966905918-Oct-13 10:25 
AnswerRe: For PerSession to increment properly.... Pin
Ajith Alex M23-Sep-14 21:01
memberAjith Alex M23-Sep-14 21:01 
GeneralMy vote of 5 Pin
Hasan Habib Surzo11-Sep-13 6:50
memberHasan Habib Surzo11-Sep-13 6:50 
QuestionMy Vote is 5 Pin
ais073-Sep-13 1:57
memberais073-Sep-13 1:57 
GeneralMy vote of 5 Pin
rwg21-Aug-13 4:39
memberrwg21-Aug-13 4:39 
QuestionExcelent !! Pin
juanchavezlive7-Aug-13 13:00
memberjuanchavezlive7-Aug-13 13:00 
GeneralMy vote of 5 Pin
Dane Balia2-Jul-13 1:40
memberDane Balia2-Jul-13 1:40 
QuestionPerfect Pin
mirko.boggian27-Jun-13 6:30
membermirko.boggian27-Jun-13 6:30 
QuestionThank you! Pin
deise_3010-Jun-13 10:38
memberdeise_3010-Jun-13 10:38 
GeneralMy vote of 5 Pin
Mohamed hammad10-Jun-13 9:59
memberMohamed hammad10-Jun-13 9:59 
QuestionSo nicely explained and simply put! Pin
axnst110-May-13 3:34
memberaxnst110-May-13 3:34 
Questioncommunication with multiple windows service hosted wcf services Pin
vaishali thaker20-Apr-13 2:10
membervaishali thaker20-Apr-13 2:10 
QuestionPoor article Pin
Member 451897613-Apr-13 17:40
memberMember 451897613-Apr-13 17:40 
GeneralMy vote of 2 Pin
Member 451897613-Apr-13 17:38
memberMember 451897613-Apr-13 17:38 
This is just another article. Nothing great about this article. One can find this information anywhere. Poor article.
GeneralMy vote of 5 Pin
babu saravanan11-Apr-13 18:29
memberbabu saravanan11-Apr-13 18:29 
GeneralMy vote of 5 Pin
PiyushSinghi9-Apr-13 17:54
memberPiyushSinghi9-Apr-13 17:54 
GeneralMy vote of 4 Pin
Morteza Azizi24-Mar-13 1:19
memberMorteza Azizi24-Mar-13 1:19 
QuestionCan I Implement this in WCF to mobile applications Pin
MathewPV20-Mar-13 1:08
memberMathewPV20-Mar-13 1:08 
AnswerRe: Can I Implement this in WCF to mobile applications Pin
Jaydeep Jadav30-May-13 3:54
memberJaydeep Jadav30-May-13 3:54 
GeneralRe: Can I Implement this in WCF to mobile applications Pin
MathewPV23-Jul-13 18:27
memberMathewPV23-Jul-13 18:27 
GeneralRe: Can I Implement this in WCF to mobile applications Pin
Jaydeep Jadav23-Jul-13 20:12
memberJaydeep Jadav23-Jul-13 20:12 
GeneralRe: Can I Implement this in WCF to mobile applications Pin
Jaydeep Jadav23-Jul-13 20:13
memberJaydeep Jadav23-Jul-13 20:13 
QuestionVery usefull Pin
Chittananda13-Mar-13 21:34
memberChittananda13-Mar-13 21:34 
QuestionMy vote is 5 Pin
sytuan28-Feb-13 23:30
membersytuan28-Feb-13 23:30 
GeneralMy vote of 3 Pin
mungflesh20-Feb-13 23:54
membermungflesh20-Feb-13 23:54 
QuestionVariable value getting changed between two sessions!! Pin
Bhavin_Shah30-Jan-13 21:15
memberBhavin_Shah30-Jan-13 21:15 
QuestionPerCall & PerSession are both return 1, Single returns 2 Pin
alexeyqian22-Jan-13 18:39
memberalexeyqian22-Jan-13 18:39 
QuestionGetting the same value while using PerSession Pin
mohandass1710-Jan-13 1:27
membermohandass1710-Jan-13 1:27 
GeneralMy vote of 5 Pin
Wei Shen5-Jan-13 19:03
memberWei Shen5-Jan-13 19:03 
GeneralMy vote of 5 Pin
vsmukesh30-Nov-12 20:56
membervsmukesh30-Nov-12 20:56 
QuestionWhich of 3 is best? Pin
eldonnadie27-Nov-12 9:41
membereldonnadie27-Nov-12 9:41 
GeneralMy vote of 5 Pin
nvskhan25-Oct-12 23:34
membernvskhan25-Oct-12 23:34 
GeneralMy vote of 5 Pin
Member 87642969-Oct-12 6:30
memberMember 87642969-Oct-12 6:30 
GeneralMy vote of 5 Pin
Jagadeesh HS26-Sep-12 3:25
memberJagadeesh HS26-Sep-12 3:25 
GeneralMy vote of 5 Pin
Member 780547425-Sep-12 4:15
memberMember 780547425-Sep-12 4:15 
QuestionGood Article Pin
Ananthikasivel17-Sep-12 22:59
memberAnanthikasivel17-Sep-12 22:59 

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 | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 9 Jun 2010
Article Copyright 2010 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid