Per Call Instance in WCF with example

Per Call Instance

In WCF there are 3 types of instancing we can do

  1. Per Call
  2. per Session
  3. Single

Per Call

When we don configuration in WCF service as per call, every call method new service instances are created

In the below example I have created on service for percall

Below example shows the details.

namespace PerCall
{
   [
ServiceContract(Namespace=" http://sujitbhujbal.blogspot.com")]
   //Created PerCall Interface
   
public interface IPerCall
   {
      [
OperationContract]
      
int IncrementCounter();
   }
 
   //PerCall session created
   [
ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
   
public class CounterServicePerCall: IPerCall
   {
      
private int m_counter;
      
int ICounterServicePerCall.IncrementCounter()
      { 
         m_counter++; 
         
MessageBox.Show(String.Format("Incrementing PerCall counter to {0}.\r\nSession Id: {1}", m_counter, OperationContext.Current.SessionId)); 
         
return m_counter;
      }
 
   }
}

In the above example i created one service that creates PerCall instance and on the every instacne Counter is incremented

Below screen shot shows the different settings and Per call instances

CallInstanceinWCF.JPG

When we click on PerCall button below screenshots shows the details what happen in PerCall

CallInstanceinWCF1.JPG

When again we press perCall session counter remains the same

CallInstanceinWCF2.JPG

Above screenshots and example shows that when we use per call instance in WCF every time call is created and counter remains same.

When should we use per call mode?

Per call

When you want a stateless services

When your WCF functions are called in a per call

References

MSDN link for WCF instances http://msdn.microsoft.com/en-us/library/ms733040.aspx

Next Recommended Reading WCF And WCF Service Components