using System; namespace DTS.Common.Classes { /// /// This is the generic for singletons. /// /// Type of derived Singleton object (i.e. class MySingletone: Singleton<MySingleton>). public class Singleton where T : new() { /// /// This is a protected constructor. /// protected Singleton() { if (!ReferenceEquals(Instance, null)) throw new InvalidOperationException("You have tried to create a new singleton class where you should have instanced it. Replace your \"new class()\" with \"class.Instance\""); } /// /// Gets the singleton instance of type T. /// public static T Instance { get { if (SingletonCreator.exception != null) throw SingletonCreator.exception; return SingletonCreator.instance; } } /// /// Creates the singleton instance of type T. /// // ReSharper disable once ClassNeverInstantiated.Local private class SingletonCreator { internal static readonly T instance; internal static readonly Exception exception; /// /// Creates the singleton instance of type T. /// static SingletonCreator() { try { instance = new T(); } catch (Exception ex) { exception = ex.InnerException ?? ex; Console.WriteLine(@"Singleton: {0}", exception); } } } } }