Dependency Injection & Singleton Design pattern

SysAdmin picture SysAdmin · Apr 18, 2010 · Viewed 46.1k times · Source

How do we identify when to use dependency injection or singleton pattern. I have read in lot of websites where they say "Use Dependency injection over singleton pattern". But I am not sure if I totally agree with them. For my small or medium scale projects I definitely see the use of singleton pattern straightforward.

For example Logger. I could use Logger.GetInstance().Log(...) But, instead of this, why do I need to inject every class I create, with the logger's instance?.

Answer

Bryan Watts picture Bryan Watts · Apr 18, 2010

Singletons are like communism: they both sound great on paper, but explode with problems in practice.

The singleton pattern places a disproportionate emphasis on the ease of accessing objects. It completely eschews context by requiring that every consumer use an AppDomain-scoped object, leaving no options for varying implementations. It embeds infrastructure knowledge in your classes (the call to GetInstance()) while adding exactly zero expressive power. It actually lessens your expressive power, because you can't change the implementation used by one class without changing it for all of them. You simply can't add one-off pieces of functionality.

Also, when class Foo depends on Logger.GetInstance(), Foo is effectively hiding its dependencies from consumers. This means that you can't fully understand Foo or use it with confidence unless you read its source and uncover the fact that it depends on Logger. If you don't have the source, that limits how well you can understand and effectively use the code on which you depend.

The singleton pattern, as implemented with static properties/methods, is little more than a hack around implementing an infrastructure. It limits you in myriad ways while offering no discernible benefit over the alternatives. You can use it however you'd like, but as there are viable alternatives which promote better design, it should never be a recommended practice.