Tuesday December 1st

Monday November 30th

Hidden Gem: Singleton Factory in C#

Simple and generic implementation of singleton factory in C#.


Ugh, I hate Blogger blogs. The comment system is so fucked up.

The pattern is okay, but there is a problem with it. Generic implies that it works everywhere (as long as the constraints are met). This pattern only works if the constructor of the object has a nonpublic constructor. You can't create a constraint for this, so there is no guarantee that the object is a singleton as the pattern cannot be enforced. You still have to rely on the coder to implement the pattern correctly, and if you have to rely on this, then its pretty much the same as saying, "Hey, only create one instance of this class per app domain, k?"

If i were to use this (and I wouldn't), I'd use reflection to see if the class has a public constructor, and if it does, I'd throw an invalid operation exception to prevent the situation described above. Its a little bit better, but still not as perfect as the static constructor singleton pattern.

I get the point. But is it a singleton pattern if you can create more than one instance per app domain? Its more of a "somewhat singleton" pattern. As a somewhat singleton, its great. No doubt about that.

There's a similar pattern implemented with a new() constraint in NGenerics.
I like it alot more than this one, because a singleton doesn't need to be a class.

This pattern is great for avoiding the non-generic singleton everywhere. The public constructor is a small disadvantage.

This is great! I think too many developers underrate the use of patterns. Design patterns provide you with so many great things (e.g. leaner code, faster ramp-up time for new developers, just to name a couple).

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network