In interviews there is always the Singleton question, I personally refuse to answer it on interview. The reason is very simple I don’t code singletons anymore. I use my IoC Container to provide me with a singleton. Sorry if you dont know what an IoC (Inversion of Control Container) is, then you are still in the old ages of coding.
For once and for all here is the hand written code of a singleton in multi-thread environment.
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
And here is in an IoC container Unity & StructureMap
//stucture map
var container = new Container(x =>
{
x.ForRequestedType().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType
();
});
//unity
myContainer.RegisterType(new ContainerControlledLifetimeManager());
As you can see one can have a singleton with one line of code in Unity and say 2 lines of code in StructureMap, so I really wonder if one needs to proof that a double check is needed in a multi thread environment for singleton.
End rant……