Static variables persisting across sessions in WCF service

c#, session, wcf

Solution

Static variables are shared across the entire process, hence the behavior you see. But if you set the service's instance context mode to per-session, then that service instance will be created per session, along with its (non-static) variables. So here `somevar` is unique to the session:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
public class Service : IService
{
    private string sessionVariable;         // separate for each session

    private static string globalVariable;   // shared across all sessions
}

Problem

I have a WCF service with sessions required ``` [ServiceContract(SessionMode = SessionMode.Required) ] ``` and some static fields. I thought that by having sessions, the static fields would remain the same for each session, but have new instances for different sessions. However, what I'm seeing when I have two different clients use the service is that when one client changes a field's value, this change also affects the other client. Is this normal behavior for having different sessions? Or do you think my service might not even be creating different sessions? I'm using netTCPbinding.

Original source