Previous | Home | Next |
PerCall service instances are created with every method call on the server side and destroyed also with every method call on the server side and When the service type is created for per-call activation, a service instance (the CLR object) exists only while a client call is in progress. Every client request gets a new dedicated service instance.
Per call activation works as given below:
- The client calls the proxy and the proxy forwards the call to the service.
- WCF creates a service instance and calls the method on it.
- if the object implements IDisposable , WCF calls IDisposable.Dispose( )on it then the method call returns.
- The proxy forwards the call to the service. when The client calls the proxy and
- WCF creates an object and calls the method on it.
To configure a service type as a per-call service, We apply the ServiceBehavior attribute with the InstanceContextMode property set to InstanceContextMode.PerCall:
[ServiceContract] interface IMyContract {...} [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] class MyService : IMyContract {...}
Per-call service and client Example:
///////////////////////// Service code ///////////////////// [ServiceContract] interface IMyContract { [OperationContract] void operation( ); } [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] class MyService : IMyContract,IDisposable { int flag = 0; MyService( ) { Trace.WriteLine("MyService.MyService( )"); } public void operation( ) { flag++; Trace.WriteLine("Counter = " + flag); } public void Dispose( ) { Trace.WriteLine("MyService.Dispose( )"); } } ///////////////////////// Client code ///////////////////// MyContractClient proxy = new MyContractClient( ); proxy.operation( ); proxy.operation( ); proxy.Close( ); //Possible Output MyService.MyService( ) Counter = 1 MyService.Dispose( ) MyService.MyService( ) Counter = 1 MyService.Dispose( )
Example of Implementing a per-call service:
[DataContract] class Exapmleofpercallservice {...} [ServiceContract] interface IMyContract { [OperationContract] void MyMethod(Exapmleofpercallservice stateIdentifier); } [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] class MyPerCallService : IMyContract,IDisposable { public void MyMethod(Exapmleofpercallservice stateIdentifier) { GetState(stateIdentifier); DoWork( ); SaveState(stateIdentifier); } void GetState(Exapmleofpercallservice stateIdentifier) {...} void DoWork( ) {...} void SaveState(Exapmleofpercallservice stateIdentifier) {...} public void Dispose( ) {...} }
Previous | Home | Next |