开发者

Singleton-Pattern ASP.NET C# for each user

开发者 https://www.devze.com 2023-01-16 05:38 出处:网络
i\'m building a web application with asp.net c# and i have a class that i want to use in multiple pages witouth instantiate it every time. I need to load the data in it and never lose them during the

i'm building a web application with asp.net c# and i have a class that i want to use in multiple pages witouth instantiate it every time. I need to load the data in it and never lose them during the user session tim开发者_如何学编程e. I thought about the singleton-pattern but it shared the instance of the class beetween browsers. How can i solve the problem?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消