What do you think about this for a generic singleton?
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);
}
}
}
}
T
directly and creating multiple? \$\endgroup\$T
, you cannot construct it normally. You have to go via theSingleton<T>
template. \$\endgroup\$string exceptionMessage = String.Format(\n"{0}...behaviour.",\nt.Name);
and thenthrow new InvalidOperationException(exceptionMessage);
right below. I also would use named arguments when callingActivator.CreateInstance
- documentation without comments. I also prefer to always have braces along with if - this is the StyleCop way, but it is up to you. \$\endgroup\$CreateInstance
that can use a private constructor to create an instance. Notice the second parameter: CreateInstance(typeof(T), true); \$\endgroup\$