Singleton-Pattern ASP.NET C# for each user

风格不统一 提交于 2019-12-06 07:36:36

Singleton is not the answer. Look at Session State, ViewState and Cookies.

UserData data = new UserData(somedata);

Session["UserData"] = data;

next page

UserData data = (UserData) Session["UserData"];

If you have inproc session state you can use something like this

class Singleton
{
    static object locker = new Object();

    public static Singleton Instance
    {
        get
        {
            var inst = HttpContext.Current.Session["InstanceKey"] as Singleton;
            if (inst == null)
            {
                lock (locker)
                {
                    inst = HttpContext.Current.Session["InstanceKey"] as Singleton;
                    if (inst == null)
                    {
                        inst = new Singleton();
                        HttpContext.Current.Session["InstanceKey"] = inst;
                    }
                }
            }
            return inst;
        }
    }
}

Code can be improved, to avoid locking for all users. Don't know if this is a good idea to implement Singleton like that, I'd recommend you to see if you can design your code in other way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!