Singleton's running on Asp.Net web applications
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;
}
}
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.
With IIS, you have no control over the thread that your request runs on. If you really need this kind of application instance level locking, you may want to look into the heavier locking objects (Mutex, Monitor, etc) and create one for each application.
If you absolutely want to ensure that they are separate, you could run each one in it's own Application Pool. That way you'd get a WP for each virtual directory.
精彩评论