I’ve learned that to have a singleton lazy loading, this is the pattern to use:
private MyObject()
{
}
public static MyObject Instance
{
get { return SingletonCreator.CreatorInstance; }
}
private static class SingletonCreator
{
private static readonly MyObject _instance = new MyObject();
public static MyObject CreatorInstance
{
get { return _instance; }
}
}
But a more simple pattern would be:
private static readonly MyObject _instance = new MyObject();
private MyObject()
{
}
public static MyObject Instance
{
get { return _instance; }
}
This wouldn’t be lazy loading. But is this really something that I should bother about in a web application?
Unless you have static methods which don’t need the singleton, just including a static constructor is enough to make the class lazy. Without the static constructor it’s still mostly lazy.
See my singleton implementation page for more details and options.
I’d normally the code you gave at the bottom of the question – it’s lazy enough, unless you really don’t want to initialize the singleton unless it’s going to be used. (Basically with
beforefieldinitset, the JIT will generally make sure that every type used in a method is initialized; withoutbeforefieldinitit has to wait until the first actual use of the class during execution. See mybeforefieldinitpage for more information – but the important point is that it’s still not going to initialize all singletons as soon as the assembly is loaded, or anything like that.)