Files
DP44/Common/DTS.CommonCore/.svn/pristine/70/70dfe40a3bbcb59ab977d3052c7aacc899dffc79.svn-base
2026-04-17 14:55:32 -04:00

61 lines
1.9 KiB
Plaintext

using System;
namespace DTS.Common.Classes
{
/// <summary>
/// This is the generic for singletons.
/// </summary>
/// <typeparam name="T">Type of derived Singleton object (i.e. class MySingletone: Singleton&lt;MySingleton&gt;).</typeparam>
public class Singleton<T> where T : new()
{
/// <summary>
/// This is a protected constructor.
/// </summary>
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\"");
}
/// <summary>
/// Gets the singleton instance of type T.
/// </summary>
public static T Instance
{
get
{
if (SingletonCreator.exception != null)
throw SingletonCreator.exception;
return SingletonCreator.instance;
}
}
/// <summary>
/// Creates the singleton instance of type T.
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Local
private class SingletonCreator
{
internal static readonly T instance;
internal static readonly Exception exception;
/// <summary>
/// Creates the singleton instance of type T.
/// </summary>
static SingletonCreator()
{
try
{
instance = new T();
}
catch (Exception ex)
{
exception = ex.InnerException ?? ex;
Console.WriteLine(@"Singleton: {0}", exception);
}
}
}
}
}