SamCogan.com

Singleton per ASP.net Session

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 session bound.

instance method of singleton:

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


Tags: ,

This entry was posted on Wednesday, January 7th, 2009 at 9:31 am and is filed under University. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>