A generic singleton

Taken from: http://andyclymer.blogspot.com/2008/02/true-generic-singleton.html
Changed by Simon Hughes 20th Feb 2008
 
using System;
using System.Reflection;
 
// Use like this
/*
public class Highlander : Singleton<Highlander>
{
    private Highlander()
    {
        Console.WriteLine("There can be only one...");
    }
}
*/
 
public class Singleton<T> where T : class
{
    private static T instance;
    private static object initLock = new object();
 
    public static T GetInstance()
    {
        if (instance == null)
        {
            CreateInstance();
        }
 
        return instance;
    }
 
    private static void CreateInstance()
    {
        lock (initLock)
        {
            if (instance == null)
            {
                Type t = typeof(T);
 
                // Ensure there are no public constructors...
                ConstructorInfo[] ctors = t.GetConstructors();
                if (ctors.Length > 0)
                {
                    throw new InvalidOperationException(String.Format("{0} has at
least one accesible ctor making it impossible to enforce
singleton behaviour", t.Name));
                }
 
                // Create an instance via the private constructor
                instance = (T)Activator.CreateInstance(t, true);
            }
        }
    }
}

Popular posts from this blog

Execution of user code in the .NET Framework is disabled

Service Broker sys.transmission_queue clean up

What do I use to write software?