I'm relatively unskilled in Dependency Injection, and I'd like to learn some best practices and anti-patterns to use and avoid respectively when using DI.
I've found that when I see a violation of the Law of Demeter that is a hint that I might want dependency injection.
For example:
void doit()
{
i += object.anotherobject.addvalue; //violation of Law of Demeter
}
Sometimes hints that I might want to dependency inject anotherobject
.
My basic rule about when to use DI is that I will inject between layers, so between my controller and the dao would be a layer, so I can inject, so that if I want to mock out a layer I can.
I think using DI within the same layer is not a good idea mainly because the layer should be tightly coupled, as they are related, unless you have a user story that makes it useful.
For example, if your DAO is may be on separate computers then you may need to be able to pretend that they are one layer, but use DI to actually switch between all on one machine and separate machines. Then the developer can do everything on one machine and it should work on separate machines.
But, unless there is some pressing need, I think DI within the same layer is an unnecessary complication.
In my opinion, Dhanji Prasanna's book Dependency Injection is a must read for software designers, both beginners and experts. It deals directly with your DI questions.
I really enjoyed this article regarding DI, as it's targeted towards people who don't have a ton of DI experience, or don't even know what it is.
What’s Unity?
It’s a “dependency injection container”.
Now, at that point a bunch of folks reading this will say “Yes, we know and we’re already using it for reasons A, B, C or we’ve elected not to use it for reasons X,Y,Z ” and I imagine a bunch of other folks might say;
“Huh? What’s a dependency injection container?”
This post is for the latter people – it’s not meant to be exhaustive but hopefully it’s not completely unhelpful either :-)