Search code examples
asp.netcachingsingletonmulti-user

Singleton in ASP.NET


If i have a singleton wrapper around a collection in asp.net does it have to be cached or would it's data be persisted across post backs?

Also if another user logs into the app would the app create another instance (of itself) and therefore another instance of the singleton or would it access the same singleton that was created in the first instance?

The actual implementation of the singleton is one of the following: (Design 1:)

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

or Design 2:

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();

   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}

Solution

  • Singleton is pattern that makes sure there is only one instance for all request. Since you have declared it static it exists for lifetime of the application. And the same instance will be returned to any user requesting the object through your property.