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;
}
}
source
share