Per-Session Service
When WCF service is configured for Per-Session instance mode, logical session between client and service will be maintained. When the client creates new proxy to particular service instance, a dedicated service instance will be provided to the client. It is independent of all other instance.
Following diagram represent the process of handling the request from client using Per-Session instance mode.
Let as understand the Per-Session instance mode using example.
Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerSession as show below.
[ServiceContract()]
public interface IMyService
{
[OperationContract]
int MyMethod();
}
Step 2: In this implementation of MyMethod operation, increment the static variable (m_Counter). Each time while making call to the service, m_Counter variable will be incremented and return the value to the client.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
public class MyService:IMyService
{
static int m_Counter = 0;
public int MyMethod()
{
m_Counter++;
return m_Counter;
}
}
Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time.
static void Main(string[] args)
{
Console.WriteLine("Service Instance mode: Per-Session");
Console.WriteLine("Client making call to service...");
//Creating the proxy on client side
MyCalculatorServiceProxy.MyServiceProxy proxy =
new MyCalculatorServiceProxy.MyServiceProxy();
Console.WriteLine("Counter: " + proxy.MyMethod());
Console.WriteLine("Counter: " + proxy.MyMethod());
Console.WriteLine("Counter: " + proxy.MyMethod());
Console.WriteLine("Counter: " + proxy.MyMethod());
Console.ReadLine();
}
All request to service return incremented value (1, 2, 3, 4), because we configured the instance mode to Per-Session. Service instance will be created once the proxy is created at client side. So each time request is made to the service, static variable is incremented. So each call to MyMethod return incremented value. Output is shown below.
Fig: PersessionOutput.
Tips!
- Always create the service with Interface->Implementation format, mention the contract in Interface.
- Define the service in Class library and refer the class library in Host project. Don’t use service class in host project.
- Change the instance mode to per call as default.
- Always catch exception using try/catch block and throw exception using FaultException < T >.
- Logging and Include exception should be enable while compiling the project in debug mode. While in production deployment disable the logging and Include exception details.