Tuesday 11 November 2008

The ASP.NET Singleton, Singleton classes for ASP.NET

This is a little trick I learned recently. I had a situation where I needed to use a static class in one of my ASP.NET web apps. I wanted it to provide functionality on a per-user basis, but when I put this in to practice I got some funny results and then I realised the obvious. Static classes are shared throughout any single instance of a .NET application, and each website runs within it's own w3wp.exe process, as a self contained application. This explained the funny behaviour.


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

3 comments:

  1. The HttpContext object cannot be called inside a static method

    ReplyDelete
  2. Hi 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.

    ReplyDelete
  3. Hey Anonymous,

    Been 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

    ReplyDelete