Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables persisting across sessions in WCF service

Tags:

c#

session

wcf

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.

like image 366
Orch Avatar asked Jul 25 '13 19:07

Orch


3 Answers

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
}
like image 152
McGarnagle Avatar answered Nov 18 '22 03:11

McGarnagle


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)

like image 23
Piotr Perak Avatar answered Nov 18 '22 02:11

Piotr Perak


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.

like image 3
vibhu Avatar answered Nov 18 '22 04:11

vibhu