Few points before choosing Singleton Pattern
- Instance will be available till Appdomain exist.
- You can not allow any parameters while creating instance of a singleton class
public sealed class MySingleton { private MySingleton() { } public static MySingleton Instance { get { return Nested.instance; } } class Nested { internal static readonly MySingleton instance = new MySingleton(); } }
But here is the twist if we create a static field initializer then the class can be marked as beforefieldinit and this will invoke the type initializer at any time before the first reference to any member
class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); }
So when we define a static constructor it means it can be accessed only any one of the member get referenced or instance is initialized of the class.
In case .NET Framework is greater than 4.0 then -
public sealed class SingletonUsingLazy { private static readonly Lazy<SingletonUsingLazy> lazy = new Lazy<SingletonUsingLazy>(() => new SingletonUsingLazy()); private SingletonUsingLazy() { } public static SingletonUsingLazy Instance { get { return lazy.Value; } } }
Thanks to Jon Skeet for writing this amazing article- Singleton Pattern