views:

349

answers:

4
+3  Q: 

ASP .NET Singleton

Hello,

Just want to make sure I am not assuming something foolish here, when implementing the singleton pattern in an ASP .Net web application the static variable scope is only for the current user session, right? If a second user is accessing the site it is a different memory scope...?

Thanks

+5  A: 

The static variable scope is for the entire app domain, which means other sessions also have access to it. Only if you have a farm with different servers you would have more than one instance of the variable.

Otávio Décio
+1  A: 

If you need it to be user or session based then check out the following link. Otherwise, as Otavio said, the singleton is available to the entire domain.

http://samcogan.com/blog/?p=27

Chris Lively
A: 

The singleton is used for the entire Application Domain, if you want to store user session-related data, use HttpContext Session which is designed for that purpose. Of course, you probably have to redesign your class structure to be able to come up with a key-value-pair way of dealing with the data you're trying to work with.

Thomas Wanner
A: 

As others have mentioned, a static variable is global to the entire application, not single requests.

To make a singleton global to only individual requests, you can use the HttpContext.Current.Items dictionary.

public class Singleton
{
    private Singleton() { }

    public static Singleton Instance 
    {   
        get
        {
            if (HttpContext.Current.Items["yourKey"] == null)
                HttpContext.Current.Items["yourKey"] = new Singleton();
            return (Singleton)HttpContext.Current.Items["yourKey"];
        }
    }
}
Dan Herbert
Thanks, What is the overhead of this? will it be much slower if I am accessing the singleton quite often?
Wesly
@Ws You shouldn't notice any performance issues with this approach. The dictionary implementation is pretty efficient so it won't slow your app down even if you access it a lot.
Dan Herbert