问题
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 time. I thought about the singleton-pattern but it shared the instance of the class beetween browsers. How can i solve the problem?
回答1:
Singleton is not the answer. Look at Session State, ViewState and Cookies.
回答2:
UserData data = new UserData(somedata);
Session["UserData"] = data;
next page
UserData data = (UserData) Session["UserData"];
回答3:
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.
来源:https://stackoverflow.com/questions/3728678/singleton-pattern-asp-net-c-sharp-for-each-user