(I previously posted this on sadeveloper.net, but since I now have my own blog, I thought I'd stick it here as well.)
To implement the singleton pattern (GoF) in ASP.NET you need to put in a bit of a twist if you want to have once instance of an object per web request. The twist I'm talking about has to do with the scope of static variables in ASP.NET. basically a static variable is visible to the whole of a process. Because of the ASP.NET process model, all client requests share the same process and thus the same singleton, this is not always the desired behaviour for example when you want to implement your database connection as a singleton, this will result in all requests sharing the same connection object and even worse, one request will try to use this connection object that was already closed by a previous request.
The solution is to implement the singleton to link the instance of your class to the specific HTTP Context instead of making it a static variable.
The following code is for a singleton class that can be used in both an ASP.NET app and a Winforms app, if a context is not found, a static variable is created as in the default implementation of the pattern.
using
System.Web;
public
class mySingleton
{
private static mySingleton oInstance;
protected mySingleton()
{
}
public static mySingleton instance()
{
if (HttpContext.Current == null)
{
if (oInstance == null)
{
oInstance = new mySingleton();
}
return oInstance;
}
if (!HttpContext.Current.Items.Contains("mySingleton"))
{
HttpContext.Current.Items.Add("mySingleton",new mySingleton());
}
return (mySingleton)HttpContext.Current.Items["mySingleton"];
}
}
The only thing to remeber here is that the key you use to add your instance to the context object must be unique.