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.
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
}
Static field is global for the life of the application. So different clients see the same static variable. If you want 'static variable' for each client then you would have to store it somehere in session state of that user (I don't know WCF well so I don't know what that means exactly in the context of WCF)
Scope of a static variable is Application Domain, this is because your actual Type (class from which instances are created) is loaded once in an application domain, and so are all its static variables and methods associated to it. So even if you have multiple instances or single instance of a service, they will share the static variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With