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?.
If you want to verify what gets logged in a test, you need dependency injection. Furthermore, a logger is rarely a singleton – generally you have a logger per each of your class.
Watch this presentation on Object-oriented design for testability and you’ll see why singletons are bad.
The problem with singletons is that they represent a global state which is hard to predict, especially in tests.
Have in mind that an object can be de-facto singleton but still be obtained via dependency-injection, rather than via
Singleton.getInstance().I’m just listing some important points made by Misko Hevery in his presentation. After watching it you will gain full perspective on why it is better to have an object define what its dependencies are, but not define a way how to create them.