Instance Context Mode in WCF
InstanceContextMode is used to control how service instances are allocated in response to client calls.
InstanceContextMode has following values:
•Single – One service instance is allocated for all client calls.
•PerCall – One service instance is allocated for each client call.
•PerSession – One service instance is allocated for each client session.
The default setting for InstanceContextMode is PerSession.
How to set InstanceContextMode ?
Steps to set InstanceContextMode in WCF :
1.Apply the ServiceBehaviorAttribute to the service class.
2.Set the InstanceContextMode property to one of the following values: PerCall, PerSession, or Single.
Per Session Service and Client
Per Session Service Code
[ServiceContract(Session = true)]
interface IMyContract
{
[OperationContract]
void MyMethod();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyService : IMyContract,IDisposable
{
int m_Counter = 0;
MyService()
{
Trace.WriteLine("MyService.MyService()");
}
public void MyMethod()
{
m_Counter++;
Trace.WriteLine("Counter = " + m_Counter);
}
public void Dispose()
{
Trace.WriteLine("MyService.Dispose()");
}
}
Client Code :
MyContractProxy proxy = new MyContractProxy();
proxy.MyMethod();
proxy.MyMethod();
proxy.Close();
Output :
MyService.MyService()
Counter = 1
Counter = 2
MyService.Dispose()
Singleton Service and Client :
Singleton Service Code :
Service Code :
[ServiceContract(Session=true)]
interface IMyContract
{
[OperationContract]
void MyMethod();
}
[ServiceContract]
interface IMyOtherContract
{
[OperationContract]
void MyOtherMethod();
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
class MySingleton : IMyContract, IMyOtherContract, IDisposable
{
int m_Counter = 0;
public MySingleton()
{
Trace.WriteLine("MyService.MyService()");
}
public void MyMethod()
{
m_Counter++;
Trace.WriteLine("Counter = " + m_Counter);
}
public void MyOtherMethod()
{
m_Counter++;
Trace.WriteLine("Counter = " + m_Counter);
}
public void Dispose()
{
Trace.WriteLine("MyService.Dispose()");
}
}
Client Code :
MyContractProxy proxy1 = new MyContractProxy();
proxy1.MyMethod();
proxy1.Close();
MyOtherContractProxy proxy2 = new MyOtherContractProxy();
proxy2.MyOtherMethod();
proxy2.Close();
Output :
MyService.MyService()
Counter = 1
Counter = 2
No comments:
Post a Comment