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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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
1 2 3 4 5 6 7 8 9 |
//stucture map var container = new Container(x => { x.ForRequestedType<IEmailService>().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType <EmailService>(); }); //unity myContainer.RegisterType<IEmailService, EmailService>(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……
Leave A Comment