Singleton runs on Asp.Net web applications

I have a question about singleton running in IIS (6,7,7,5) and ASP.NET 4.0 web application (e.g. for MVC3 application).

I have a singleton object in my project that is accessed and used in global.ascx, on application_start, as well as in several other places in the application.

My concern is that this singleton should be available for each scenario. However, since IIS is primarily a hosting process, is singleton the same object in all instances of the application?

If I use the [ThreadStatic] keyword, is it split at the application pool level?

Finally, is there a way, I can assure you that singleton is just one instance for my application. that is, if I run my application on one website, but there are 5 singleton instances in 5 virtual directories, or I launch my site on 5 different sites in the same application pool.

Hope this is clear enough if you want to see a singleton object, I applied the general idea of ​​this below.

public sealed class Singleton : IDisposable
{
    [ThreadStatic]
    private static volatile Singleton _instance;
    [ThreadStatic]
    private static readonly object _syncRoot = new object();

    public bool IsReleased { get; private set; }

    public Singleton()
    {
        IsReleased = false;
    }

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_syncRoot)
                {
                    if (_instance == null)
                        _instance = new Singleton();
                }
            }

            return _instance;
        }
    }

    public void Dispose()
    {
        IsReleased = true;
        Singleton._instance = null;
    }
}
+5
source share
3 answers

The static value must be static in a specific instance of your web application, so each instance of your application will have its own instance, which will be used for all threads in this instance.

. http://msdn.microsoft.com/en-us/library/2bh4z9hs(v=vs.71).aspx

, ThreadStatic , . , .

+3

IIS , . , (Mutex, Monitor ..) .

0

, , . , WP .

0
source

All Articles