61 lines
1.9 KiB
Plaintext
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<MySingleton>).</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);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|