Friday, 14 October 2011

Instance Deactivation

In Instance Management System tutorial, you learn how to create sessionful service instance. Basically service instance is hosted in a context. Session actually correlated the client message not to the instance, but to the context that host it. When session starts, context is created and when it closes, context is terminated. WCF provides the option of separating the two lifetimes and deactivating the instance separately from its context.
ReleaseInstanceMode property of the OberationalBehavior attribute used to control the instance in relation to the method call.
Followings are the list Release mode available in the ReleaseInstanceMode
  1. RealeaseInstanceMode.None
  2. RealeaseInstanceMode.BeforeCall
  3. RealeaseInstanceMode.AfterCall
  4. RealeaseInstanceMode.BeforeAndAfterCall
Below code show, how to add the 'ReleaseInstanceMode' property to the operational behavior.
    [ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
   [OperationBehavior(ReleaseInstanceMode=ReleaseInstanceMode.BeforeCall]
    public int Add(int num1, int num2)
    {
        return num1 + num2;            
    }

ReleaseInstanceMode.None

This property means that it will not affect the instance lifetime. By default ReleaseInstanceMode property is set to 'None'.

ReleaseInstanceMode.BeforeCall

This property means that it will create new instance before a call is made to the operation.
If the instance is already exist,WCF deactivates the instance and calls Dispose() before the call is done. This is designed to optimize a method such as Create()

ReleaseInstanceMode.AfterCall

This property means that it will deactivate the instance after call is made to the method.
This is designed to optimize a method such a Cleanup()

ReleaseInstanceMode.BeforeAndAfterCall

This is means that it will create new instance of object before a call and deactivates the instance after call. This has combined effect of using ReleaseInstanceMode.BeforeCall and ReleaseInstanceMode.AfterCall

Explicit Deactivate

You can also explicitly deactivate instance using InstanceContext object as shown below.
   [ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        void MyMethod();
    }

   
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class MyService:IMyService
    {

        public void MyMethod()
        {
           //Do something
           OperationContext.Current.InstanceContext.ReleaseServiceInstance();
            
        }       
    }
 

No comments:

Post a Comment