So I did a little digging around and found the following code, which adapts the singleton pattern to store the instance in a per-user manner.
Each user is assigned an HttpContext for thier time visiting an ASP.NET web application. This Context object allows you to store objects.
So a classic Singleton might look something like this
class Singleton {
// private instance field
private static Singleton _instance;
// public read-only instance property
public static Singleton Instance {
get{
if(_instance == null){
_instance = new Singleton();
}
return _instance;
}
}
// private constructor
private Singleton() {
// constructor logic here
}
}
All we have to do is to replace the private field for an Item in the HttpContect object, like so...
class Singleton {
// public read-only instance property
public static Singleton Instance {
get{
if(HttpContext.Current.Items["SingltonInstance"] == null){
HttpContext.Current.Items.Add("SingltonInstance", new
Singleton());
}
// cast the item to a singleton because it is stored as a generic object
return (Singleton)HttpContext.Current.Items["SingltonInstance"];
}
}
// private constructor
private Singleton() {
// constructor logic here
}
}
The HttpContext object cannot be called inside a static method
ReplyDeleteHi Anonymous, This pattern has worked fine for me on more than one project and I've seen nothing in the MSDN docs to suggest that the HttpContext cannot be called from a static situation. Could you link me up please.
ReplyDeleteHey Anonymous,
ReplyDeleteBeen as you got me a bit nervous I thought I'd ask on stackoverflow.
Check this link out http://stackoverflow.com/questions/556310/httpcontext-current-accessed-in-static-classes