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
}
}