Click here to Skip to main content
14,773,758 members
Articles » Platforms, Frameworks & Libraries » Windows Communication Foundation » General
Posted 21 Aug 2012


83 bookmarked

Implementing WCF Service Behaviors

Rate me:
Please Sign up or sign in to vote.
4.95/5 (46 votes)
22 Aug 2012CPOL
Here we will try to implement different service behaviors to increase service performance


This article will explain how we can achieve through puts, reliability and performance using various WCF Service behavior techniques. Most application differs widely in their scalability and performance strategies. WCF service behaviors provide various possible ways to configure key run time behaviors. We will go through various service behavior elements one by one.  


By default WCF service handles only single request at a time and all other service request threads are queued and processed one by one. Concurrency element allows clients to send multiple requests at the same time, but service implementation should be break free of scenarios like dead locks. 

There are three types of Concurrency modes.   

  1. Single(Default): Concurrency mode single will allows only one at a time to the service instance. And all other pending requests will be maintained in queue and processed one by one. Whenever a new request comes dispatcher gets a lock before entering in to the code. Refer Figure 1. 
  2. Image 1

    Figure 1. 

    ConcurrencyMode Single is defined as follows: 

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
    public class VisitorCount : IVisitorCount
  3. Multiple: This will allow parallel requests, and that are processed at the same time by spawning separate thread for each and every request. Refer Figure 2.
  4. Image 2

    Figure 2

    Here is how we would define ConcurrencyMode Multiple.

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class VisitorCount : IVisitorCount
  5. Re-entrant: Whenever a client calls WCF service a thread lock will be assigned to this client call. Let us consider a scenario where Service 1 makes an external call to Service 2. Thread lock won’t be released until entire service call is completed. So all other client requests are in waiting state. Re-entrant allows the client to release the lock before making call to the external service (Service 2) and this will allow other client to use the Service 1 facilities until Service 2 process is completed. Refer Figure 3. 
  6. Image 3

    Figure 3 

    Decorating service class with ConcurrencyMode Reentrant

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class VisitorCount : IVisitorCount

Concurrency mode can increase the amount of passing through the service methods and hence overall service performance increases. 

Instance Context Mode  

WCF Instancing decides how objects are created and refers to the life time of the service object. Whenever clients make request runtime will create service objects to provide the response. Through instancing we ca control how long this service instance wants to be retained. For that we are using the three instancing modes. 

  1. Per Call: In this scenario, all the calls to the service become stateless. And for every thread request a new service instance will be created. This will work with all the service bindings. Refer Figure 4. 
  2. Image 4

    Figure 4.

    Here is how we would define InstanceContext Mode Percall.

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,
           InstanceContextMode = InstanceContextMode.PerCall)]
    public class VisitorCount : IVisitorCount
  3. Per Session: The life time of service object is independent of the life time of Client channels, so  this will create a new service object whenever a new communication session is established and disposed after that. Each client channel gets a dedicated service instance and the subsequent calls in the same session are handled by the same Service object. This is the default value for Instancing Context. And this will work with all bindings except basicHttpBindings. Refer Figure 5. 
  4. Image 5

    Figure 5.

    Here is how we would define InstanceContextMode PerSession.

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,InstanceContextMode = InstanceContextMode.PerSession)]
    public class VisitorCount : IVisitorCount
  5. Single: This will help us to share the data globally. We can create only one instance and the same instance will be reused on the subsequent calls. Same like Per Session this will work with all bindings except basicHttpBinding. Single ton instance will not be disposed until service host is down. Refer Figure 6.
  6. Image 6

    Figure 6

    Here is how we would define InstanceContext mode Single.

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,InstanceContextMode = InstanceContextMode.Single)]
    public class VisitorCount : IVisitorCount

Service Throttling  

WCF allows you to throttle load on a particular service type.

This includes 

  1. Maximum number of Concurrent sessions  
  2. Maximum number of Concurrent calls 
  3. Maximum number of Concurrent instances  

Whenever these values exceeded, the callers will be added to the queue and processed FIFO order. We can configure throttling behavior in application configuration file as follows. 

<behavior name="visitorCountServiceBehavior"> 
<serviceThrottling maxConcurrentCalls="5" maxConcurrentInstances="10" maxConcurrentSessions="10"> 

Using the code   

Let us create a sample application to demonstrate different service behaviors. First create an interface and decorate it with  ServiceContract and OperationalContract attributes to specify that these operations of this interface can be used by the client applications.

public interface IVisitorCount
int GetVisitorCount();

Now we have to create a service class to implement above interface method. And we have to decorate service class with different service behaviors, following code explains Concurrency Mode Single and Instance context mode single.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,InstanceContextMode = InstanceContextMode.Single)]
public class VisitorCount : IVisitorCount
  int _visitorCount = 0;
  public VisitorCount()
      Console.WriteLine("New Service Instance Created");
  public int GetVisitorCount()
   return _visitorCount;

Now let us see how we can make this service available to client applications, Configuration file App.Config contents are given below.

    <compilation debug="true">
      <service name="InstanceContextModeService.VisitorCount">
        <endpoint binding="wsHttpBinding" contract="InstanceContextModeService.IVisitorCount">
            <dns value="localhost">
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
            <add baseaddress="http://localhost:8732/InstanceContextModeService/VisitorCount/">
          <servicemetadata httpgetenabled="True">
          <servicedebug includeexceptiondetailinfaults="False">
          <servicethrottling maxconcurrentcalls="5" maxconcurrentinstances="10" maxconcurrentsessions="10">

Following service host code will host VisitorCounter service to the client applications.

class Program
  private static ServiceHost host = null;
  static void Main(string[] args)
     host = new ServiceHost(typeof(InstanceContextModeService.VisitorCount));
     host.Opened += new EventHandler(host_Opened);
     host.Closed += new EventHandler(host_Closed);
  static void host_Closed(object sender, EventArgs e)
     Console.WriteLine("Service Closed");
  static void host_Opened(object sender, EventArgs e)
    Console.WriteLine("Service Started");

We have our service is hosted and defined. Following code explains how clients utilize service and service behaviors.

static class Program
 static void Main(string[] args)
    VisitorCountClient client = new VisitorCountClient();
    Console.WriteLine("First Call-->" + client.GetVisitorCount());
    Console.WriteLine("Second Call-->" + client.GetVisitorCount());
    Console.WriteLine("Third Call-->" + client.GetVisitorCount());
    Console.WriteLine("Forth Call-->" + client.GetVisitorCount());

Download above attached sample application for your reference and go through different service behaviors by changing different behavior attributes as we discussed earlier.


Whenever we design an enterprise application, it should provide great performance, scalability, through puts and reliability. WCF can achieve these features with different technologies discussed in this piece of writings. 


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


About the Author

Vinod Viswanath
Engineer GE Oil & Gas
India India
Vinod is Microsoft Certified Professional in WebDev 4, And Lead Engineer by profession. He has more than 8+ yrs of experience in IT industry working on Microsoft Technologies. Prefer to be judged not on his job title but by ability to do a good job of what he is supposed to do.

Technical experience most specifically C#,Ado.Net,Asp.Net, WCF, Sql Server,JavaScript,XML,Web services.

Comments and Discussions

Questionapp.config has a mistake Pin
Member 127271272-Jan-18 18:19
MemberMember 127271272-Jan-18 18:19 
GeneralMy vote of 4 Pin
Manas_Kumar10-Dec-15 1:40
professionalManas_Kumar10-Dec-15 1:40 
QuestionGood Job. Pin
shiva guduri4-Aug-14 5:25
Membershiva guduri4-Aug-14 5:25 
QuestionVery Nice Pin
pradeep surya23-Jun-14 20:59
Memberpradeep surya23-Jun-14 20:59 
GeneralComments Pin
RajeshKumar Sugumar3-Apr-14 16:31
MemberRajeshKumar Sugumar3-Apr-14 16:31 
QuestionRemark Pin
Member 998102226-Nov-13 19:50
MemberMember 998102226-Nov-13 19:50 
GeneralWell worded. Pin
db7uk19-Jan-13 12:43
Memberdb7uk19-Jan-13 12:43 
GeneralMy vote of 5 Pin
wsc09187-Jan-13 19:27
Memberwsc09187-Jan-13 19:27 
GeneralMy vote of 5 Pin
Raghunatha_Reddy_S13-Dec-12 22:45
MemberRaghunatha_Reddy_S13-Dec-12 22:45 
GeneralMy vote of 5 Pin
viragdesai15-Nov-12 18:58
Memberviragdesai15-Nov-12 18:58 
GeneralMy vote of 5 Pin
Md. Marufuzzaman14-Sep-12 3:05
professionalMd. Marufuzzaman14-Sep-12 3:05 
GeneralMy vote of 5 Pin
Sandip.Nascar11-Sep-12 22:36
MemberSandip.Nascar11-Sep-12 22:36 
QuestionNice work.. Pin
pankajcode5-Sep-12 8:01
Memberpankajcode5-Sep-12 8:01 
GeneralMy vote of 5 Pin
Anuraj Parameswaran3-Sep-12 0:25
MemberAnuraj Parameswaran3-Sep-12 0:25 
GeneralMy vote of 5 Pin
Steve Xaviour29-Aug-12 1:55
MemberSteve Xaviour29-Aug-12 1:55 
GeneralGreat post was really searching for one.......... Thanks a lot vinod..... Pin
sarathbtech@gmail.com28-Aug-12 16:40
Membersarathbtech@gmail.com28-Aug-12 16:40 
GeneralMy vote of 5 Pin
swapnilcodeproject27-Aug-12 0:40
Memberswapnilcodeproject27-Aug-12 0:40 
GeneralMy vote of 5 Pin
falconfrancis27-Aug-12 0:25
Memberfalconfrancis27-Aug-12 0:25 
GeneralMy vote of 5 Pin
maq_rohit22-Aug-12 19:25
professionalmaq_rohit22-Aug-12 19:25 
GeneralMy vote of 5 Pin
Christian Amado22-Aug-12 10:30
professionalChristian Amado22-Aug-12 10:30 
GeneralMy vote of 5 Pin
Shanky127722-Aug-12 9:14
MemberShanky127722-Aug-12 9:14 
GeneralMy vote of 3 Pin
morningstar171022-Aug-12 4:24
Membermorningstar171022-Aug-12 4:24 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey21-Aug-12 19:35
professionalManoj Kumar Choubey21-Aug-12 19:35 

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

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