Singleton pattern in web applications

前端 未结 5 1227
萌比男神i
萌比男神i 2021-02-05 21:46

I\'m using a singleton pattern for the datacontext in my web application so that I dont have to instantiate it every time, however I\'m not sure how web applications work, does

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 22:00

    Static variables are visible to all users on the per app domain, not per session. Once created, the variable will sit in memory for the lifetime of the app domain, even if there are no active references to the object.

    So if you have some sort of stateful information in a web app that shouldn't be visible to other users, it should absolutely not be static. Store that sort of information in the users session instead, or convert your static var to something like this:

    public static Data SomeData
    {
        get
        {
            if (HttpContext.Session["SomeData"] == null)
                HttpContext.Session["SomeData"] = new Data();
            return (Data)HttpContext.Session["SomeData"];
        }
    }
    

    It looks like a static variable, but its session specific, so the data gets garbage collected when the session dies and its totally invisible to other users. There safety is not guaranteed.

    Additionally, if you have stateful information in a static variable, you need some sort of syncronization to modify it, otherwise you'll have a nightmare of race conditions to untangle.

提交回复
热议问题