Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton's running on Asp.Net web applications

Tags:

c#

asp.net

iis

I have a question about Singletons running within IIS (6,7,7.5) and an ASP.NET 4.0 Web Application (MVC3 app to be specific).

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

My concern is, this singleton needs to be accessable at a per instance scenario. However, since IIS is essentially the hosting process, is the singleton going to be the same object across all instances of the application?

If I use the [ThreadStatic] keyword, does it seperate at the Application Pool level?

Finally, is there a way, I can assure a singleton is only a singleton per instance of my application. i.e. if I run my application on 1 website, but inside 5 virtual directories, there is 5 instances of the singleton or if I run my website on 5 different websites within the same application pool.

Hopefully that's clear enough, incase you wanted to see the singleton object, I pasted the general idea of it 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;
    }
}
like image 485
John Avatar asked Oct 26 '22 00:10

John


1 Answers

A static value should be static across a particular instance of your web application, so each instance of your application will have its own instance that will be shared across all threads on that instance.

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

Oh, and the ThreadStatic attribute will cause the static value to only be static across a particular thread, so every request would have its own version of that field. It doesn't sound like this is what you're going for.

like image 114
StriplingWarrior Avatar answered Nov 15 '22 05:11

StriplingWarrior