I am pretty new in WCF and trying to understand various instance management techniques, I am able to understand Per-Call & Singleton instance mode but i am confused in per session instance mode, In this case for every client a separate session is created right? But its not happening in my case:
My WCF Service:-
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession )]
public class CounterService : ICounterService
{
int _counter = 0;
public int GetCount()
{
_counter++;
return _counter;
}
}
Client Code:-
static void Main(string[] args)
{
CounterServiceReference.CounterServiceClient proxy = new CounterServiceReference.CounterServiceClient();
CounterServiceReference.CounterServiceClient proxy1 = new CounterServiceReference.CounterServiceClient();
Console.WriteLine("WCF Instance mode: Per Session");
Console.WriteLine("Invoking WCF service...");
Console.WriteLine("Counter: {0}", proxy.GetCount());
Console.WriteLine("Counter: {0}", proxy.GetCount());
Console.WriteLine("Counter: {0}", proxy.GetCount());
Console.WriteLine("---------------------------------------");
Console.WriteLine("Counter: {0}", proxy1.GetCount());
Console.WriteLine("Counter: {0}", proxy1.GetCount());
Console.WriteLine("Counter: {0}", proxy1.GetCount());
Console.ReadKey();
}
But, console is displaying result as 1,1,1---1,1,1 but i think it should be 1,2,3---1,2,3 Am i wrong somewhere? Please Help! TIA
The following instancing modes are available: PerCall: A new service instance is created for each client request. PerSession: A new instance is created for each new client session, and maintained for the lifetime of that session (requires a binding that supports session).
The set of techniques employed by WCF for binding a set of messages (client requests) to service instances is known as Instance Management.
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.
WCF can maintain a session between a client and a particular service instance.
I think perhaps the best way to explain it is via these diagrams (borrowed from a CodePlex article on the topic):
The main concept to grock is that when a given client creates a proxy to a service in the PerSession mode, repeated calls to that service from that proxy will be calling the same service instance (specific to that client). This allows you to store some state in your service object for a client, since each client gets their own service object instance.
This contrasts with PerCall and Singleton as follows:
When you create a proxy to a PerCall service, you get a fresh, new instance of the service object every time you invoke a service operation.
When you create a proxy to a SingleTon service, there is only one instance of that service handling all client requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With