The Singleton Pattern

6 Dec

One of my favorite gang of four patterns is the singleton pattern. The singleton pattern is a “Gang of Four” design pattern which is commonly used for maintaining one common instance of an object that is widely accessible. For C# implementations of the singleton pattern I previously used the 4th pattern on the following site: Recently however I have come to find issue with the singleton patterns in C# on two fronts. The first front being WPF view models. The second being from a Test Driven Development (TDD) perspective.

  1. The first point I have about the singleton pattern is that if you require the ability to subclass an existing class it becomes an anti-pattern. An example with WPF could be the requirement to adopt depenedency properties on a class. You could then argue that a class could be used to provide a single instance of the object. This would work for C# code, but it is problematic for XAML.  It is possible to maintain a single instance of a class in XAML with the ObjectDataProvider tag but then you would need to find that instance from the pages resources (usually a resource dictionary).  As I mentioned in a earlier post, it is important to me architecturally that XAML controls/resources are not directly referenced unless absolutely necessary.
  2. The second point is possibly more globally recognized, that singleton pattern is an anti-pattern when trying to unit test a class. For more on this you can google with the keywords of “singleton unit test” or check out the following blog post:

The singleton is still a great concept and a great tool to have in a developers arsenal but now I take a different approach by using an IoC (Inversion of Control/Dependency Injection) container called ninject which provides a Singleton attribute which provides uses the IoC facilities to maintain a reference to a single instance of an object. I feel that this approach will play well with WPF databinding because I believe the attribute will allow calls to be directed at the class without having knowledge of the factory maintaining the instance (Note: yet to confirm this in practice). I believe that other developers have opted for adopting service locators instead of singleton patterns. A blog post about the argument of IoC vs Service Locators is provided here:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: