Injecting dependencies doesn't have to hurt

December 4, 2010 Dependency Inversion Principle (DIP)

I have noticed a recent swell of comments about the pain of dependency injection, and if this has caused you problems on your project, then I think I can help you by offering a few simple guidelines and a single goal for injecting dependencies.


This is a companion discussion topic for the original entry at http://blog.thecodewhisperer.com/permalink/injecting-dependencies-doesnt-have-to-hurt

great, looking forward to future articles/examples

Also looking forward to the sequel. Any indication of when it's going to arrive?

Unfortunately, I don't have any schedule for these articles.

Could you explain why you suggest "
When in doubt, inject each dependency directly into the method that requires it."? I always pass all dependencies through constructors and get well known feedback - if the number of dependencies starts getting out of hand (I prefer not more than three, two is better), then the SRP is violated and the class should be split into smaller ones. If dependencies are passed here and there into methods, it's hard to detect the moment when class is bigger than we like it to be. Am I missing something?

I mean specifically that if you're not sure whether a collaborator belongs in the constructor or with only the method, then choose only the method until you see multiple methods using it, then promote it into the constructor.

You could also say that one should follow the Dependency Inversion Principle. I believe that novice and advanced beginner developers should be reminded of SOLID design principles, before they get excited about shiny DI frameworks.

I agree. I believe that following these rules will lead you to following the Dependency Inversion Principle, particularly the one about injecting dependencies into methods or the constructor. If you do this and remove duplication mercilessly, you'll (re)discover DIP.