Home > Development > WCF Instance De-Activation

WCF Instance De-Activation

September 29, 2010 Leave a comment Go to comments

So we are going to take a look at WCF Instance de-activation.

When you have the InstanceContextMode to Per Call the service instance is deactivated at the end of the call.
When you have the InstanceContextMode to Per Session the service instance is deactivated at the end of the session or after timeout.
When you have the InstanceContextMode to Single the service instance is deactivated at the shutdown of the application.

You need to apply the ReleaseInstanceMode as shown below. The options are pretty self explanatory as to when to release the service instance.

You can also do it in code using OperationContext.Current.InstanceContext.ReleaseServiceInstance() as shown in the code.

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WCFInstanceActivation.Server
{
    [ServiceContract(Namespace = "http://localhost/Samples", SessionMode = SessionMode.Required)]
    interface IPrintService
    {
        [OperationContract]
        void Print(string message);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    class PrintService : IPrintService
    {

        [OperationBehavior(ReleaseInstanceMode = ReleaseInstanceMode.BeforeCall)]
        public void Print(string message)
        {
            Console.WriteLine(message);
            OperationContext.Current.InstanceContext.ReleaseServiceInstance();

            Console.WriteLine("Continuing with session id: " + OperationContext.Current.SessionId);
        }
    }

    class Program
    {
        static void Main()
        {
            using (ServiceHost host = new ServiceHost(typeof(PrintService), new Uri("http://localhost/PrintService")))
            {

                host.AddServiceEndpoint(typeof(IPrintService), new WSHttpBinding(), "");
                host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
                //host.Description.Behaviors.Add(new ServiceDebugBehavior{ IncludeExceptionDetailInFaults = false});

                host.Open();

                Console.WriteLine("Press any key to quit..");
                Console.ReadKey();
            }
        }
    }
}

Hope this helps..

Blair..

Advertisements
Categories: Development Tags: , , , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: