I\'ve been looking at the article on creating static constructors in c# here:
http://csharpindepth.com/Articles/General/Singleton.aspx
Now, one option he doesn\'
Your code isn't building a singleton. It's creating an instance of Foo
, and presumably anyone else could too - which means it isn't a singleton.
You've created a single instance which is referred to by a static variable in ServiceFactory
, but that's not the same thing.
Unless you have some class which you've restricted so that there can only ever be one instance of it, you don't have a singleton. You may have a factory pattern, a cache, whatever - but you don't have a singleton.
Now what you've got is equivalent to this:
static Foo container = new Foo();
static ServiceFactory()
{
}
... and I'm not sure why you think your version is simpler than the above. If you do want to actually create a singleton, you're going to need a private constructor for whatever class you're trying to turn into a singleton. At that point, you've basically got my fourth example, so again I'm not sure where you think you're making things simpler.
Of course, you may not need a static constructor at all - it depends on how precise you need the timing to be. (Read my article on beforefieldinit for more details, along with my blog post about the CLR v4 changes.)
The question of the day is this: do you want lazy instantiation or not? If you do not need lazy instantiation and are perfectly fine with on-load instantiation, feel free to use the paradigm you have, or even use this somewhat less verbose version:
public static class ServiceFactory
{
private static readonly container = new Foo();
public static Instance { get { return container; } }
}
Both work fine and are perfectly valid -- as long as you don't need lazy. If you need lazy, use the Fifth version pointed out in the article.
Your code is equivalent to his fourth example†, except you are using an explicit class constructor whereas he is initialising at point of declaration.
You should (in most cases) shy away from using the singleton pattern, as it makes it very hard to scale and unit-test an application.
† except there is a behavioural difference as to when the singleton is constructed when class constructors are used.