wm1sr
wm1sr

Reputation: 2015

Instance state not being preserved using InstanceContextMode.PerSession

I'm building a WCF application and I need to preserve the instance state of the service between sessions. My service implementation looks like this:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IService {
    private int i;

    public int Increment() {
        return i++;
    }
}

I need to preserve the value of the i variable between each session. However, InstanceContextMode.PerSession seems to be doing the same thing as InstanceContextMode.PerCall. So if call Increment() a couple of times in the client application I get 0 every time:

var serviceClient = new ServiceClient();
MessageBox.Show(serviceClient.Increment()); // 0
MessageBox.Show(serviceClient.Increment()); // 0

I tested the same thing using InstanceContextMode.Single and it works as expected but this behavior does not suit my needs because the instance state of the service cannot be preserved between clients.

Upvotes: 1

Views: 100

Answers (1)

Derek W
Derek W

Reputation: 10026

I am going to go out on a whim and assume you are using BasicHttpBinding.

BasicHttpBinding does not support sessions due to the connectionless nature of HTTP. Any binding that does not support reliable sessions or if the ReliableSession property of the binding is set to false, then the service will behave as PerCall.

You can view which bindings support reliable sessions here and you can view the details into InstanceContextMode here.

Upvotes: 1

Related Questions