title: Singleton's running on Asp.Net web applications
body: <p>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).</p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>If I use the [ThreadStatic] keyword, does it seperate at the Application Pool level?</p>
  
  <p>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.</p>
  
  <p>Hopefully that's clear enough, incase you wanted to see the singleton object, I pasted the general idea of it below.</p>
  
  <pre><code>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;
      }
  }
  </code></pre>