Single instance of a class per HTTP request Single instance of a class per HTTP request asp.net asp.net

Single instance of a class per HTTP request


HttpContext.Current is the HttpContext object for the current request. It has an Items property which is an IDictionary from object to object. You can put anything you like in there, and it will be tied to the current request.


Can you check in the constructor of your singleton to see if that object exists in the session? If not, create it and then return it?

private Singleton(){    // do whatever}public Singleton GetMySingleton(){    if(HttpContext.Current.Items["MyCustomSingleton"] == null)        HttpContext.Current.Items["MyCustomSingleton"] = new Singleton();    //    return (Singleton)HttpContext.Current.Items["MyCustomSingleton"];}