Showing posts with label Static Classes. Show all posts
Showing posts with label Static Classes. Show all posts

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