Singleton Per ASP.net Session

>This is a re-publish of a post from my old blog, but was being requested by a number of people.

A class in my current project is accessed multiple times in a session, and stores error messages that need to be read by multiple classes, so I wanted to make this class a singleton.

However a singleton in asp.net is then available to the whole application, not something I want, as error messages are per user. So after some experimenting, I came up with a simple way to make your singleton a session bound, instance method of singleton:

language-c#
public singleton Instance {
get {
string name = "singleton";
if (HttpContext.Current.Session[name] == null)
HttpContext.Current.Session[name] = new MyClass();
return (singleton)HttpContext.Current.Session[name];
}
}

About the author

samcogan

Follow Me

Follow me on Twitter