Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
I like to use singletons in my applications, especially when i don't want to initialise a class all the time when i need it. The idea behind a singleton class is to get an instance by calling a static member method and not be able to instantiate the class yourself. In that way there will only be one instance of the class during the run of the application. This is accomplished by making the constructor protected. Normally a singleton class is used in a windows application as follow:
class SomeClass{ private static SomeClass instance = null;
protected SomeClass() { }
public static SomeClass Instance { get { if (instance == null) { instance = new SomeClass(); }
return instance; } }}
When you want to use the same trick in an ASP.NET application it will not work, because everytime the class is destroyed when the content of your page is rendered to the client. But even singletons are usefull in ASP.NET applications and there is a solution by using for example the session state. The following code shows you how:
class SomeClass{ protected SomeClass() { }
public static SomeClass Instance { get { object instance = System.Web.HttpContext.Current.Session["SomeClassInstance"]; if (instance == null) { instance = System.Web.HttpContext.Current.Session["SomeClassInstance"] = new SomeClass(); }
return instance as SomeClass; } }}
As you can see it just stores the instance in a session state. You could even store the instance in the application state if there is need for. It could be helpfull for your ASP.NET application. :)