Managing State in WCF
Managing State in WCF
By : Kasim Wirama, MCDBA, MVP SQL Server
Similar to web service, WCF could contain several methods, for some client scenarios, each methods is independent among another, but for some client scenarios, some methods are dependent each other, sharing same property member in interface implementation. In this sharing perspective, it is called state. WCF gives you options how you manage your state.
State management is put as an attribute of interface implementation of a class. The class attribute is ServiceBehaviour, the class has InstanceContextMode property. 3 possible value for this InstanceContextMode:
1. PerSession (default)
Each client has its own session. Session will terminate if client closes its proxy.
Another property that relates to this is ConcurrencyMode, default is Single, if you set to Multiple, service instance will be in multithreaded mode instead of single threaded, synchronization issue will happen in multithreaded mode.
2. PerCall
Session is limited only for each method call. State is not maintained in this mode, but it’s scalable.
3. Single
All client connection shares 1 session in WCF service.
You can try each one of them. I create more than one method in WCF Service Contract like below
[OperationContract(Name = "StringMethod")]
string StringMethod();
[OperationContract(Name = "Add")]
int Add(int a, int b);
[OperationContract(Name = "Multiply")]
int Multiply(int a, int b);
[OperationContract(Name = "AddTwo")]
int AddTwo(int a);
[OperationContract(Name = "MultiplyTwo")]
int MultiplyTwo(int a);
In interface implementing class, add attribute [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] and implement each of the method as specified in WCF Service Contract.
Add HTTP endpoint in application/web configuration at WCF host with WCF configuration editor window, referring to DLL where WCF service contract resides, then specify communication mode with advanced simplex web service interoperability, and specify the endpoint.
Because service contract has already changed, regenerate the client proxy, and add to WCF client. Rebuild your WCF client project, and add new client endpoint. And add code below :
OperationImpl.OperationClient proxy=new OperationClient("myclient ");
proxy.Open();
proxy.StringMethod();
int a, b;
a = 5;
b = 6;
Console.WriteLine("original value a : {0} and b : {1}", a, b);
int result;
result= proxy.Add(a, b);
Console.WriteLine("add result : {0}",result);
result = proxy.Add(a, b);
Console.WriteLine("add result : {0}", result);
Run your WCF client, first value after first proxy.Add will be 11, second one will be 22. Raising other WCF client instance will display same result.
If you change InstanceContextMode to PerCall, first Add will be 11, second add still will be 11.
If you change InstanceContextMode to Single, first Add will be 11, second add still will be 22. Raising other WCF client instance, the first Add will be 33 and second Add will be 44