WCF instanceContextMode

With WCF, you can configure lot of thing.

An interesting setting is the InstanceContextMode

MSDN talk about that :  « Use the InstanceContextMode property to specify when new service objects are created. Because the service object is not directly connected to the communicating channel, the lifetime of the service objects is independent of the lifetime of the channel between a client and the service application. The default value, PerSession, instructs the service application to create a new service object when a new communication session is established between a client and the service application. Subsequent calls in the same session are handled by the same object. » (http://msdn.microsoft.com/library/system.servicemodel.servicebehaviorattribute.instancecontextmode.aspx)

InstanceContextMode property got three value :

  • Single
  • PerSession
  • PerCall
To see the effect I made a simple service which update or get a String value, we’ll see when you retrieve the value in the same client or in another client.
Here is the contract :

[ServiceContract]

    public interface IContractSample

    {

        [OperationContract]

        String GetStringValue();

 

        [OperationContract]

        void UpdateStringValue(String sNewValue);

    }

Now the implementation of the service :

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class ServiceCode : IContractSample
    {
        public String svalue = "test";
        public string GetStringValue()
        {
            return svalue;
        }

        public void UpdateStringValue(String sNewValue)
        {
             svalue = sNewValue;
        }
    }

 

The first Mode is PerSession, here is the behavior :


As we can see a client cannot interact in another client session.

The next InstanceContextMode is PerCall,


As we can see no session have been saved between the two calls. this mode is very usefull when every method are independant

The last Mode is Single :

In this mode there is only one Service instance, all member are shared, very useful when you need to implement a singleton

Publicités

Laisser un commentaire

Choisissez une méthode de connexion pour poster votre commentaire:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s