I was reading over Injection by Hand and Ninjection (as well as Why use Ninject ). I encountered two pieces of confusion:
The inject by hand technique I am already familiar with, but I am not familiar with Ninjection, and thus am not sure how the complete program would work. Perhaps it would help to provide a complete program rather than, as is done on that page, showing a program broken up into pieces
I still don't really get how this makes things easier. I think I'm missing something important. I can kind of see how an injection framework would be helpful if you were creating a group of injections and then switching between two large groups all at once (this is useful for mocking, among other things), but I think there is more to it than that. But I'm not sure what. Or maybe I just need more examples of why this is exciting to drive home the point.
Using a dependency injection framework helps make the program flexible and makes it easier to specify how it will operate (within well defined parameters of course).
Basically, dependency injection makes some (usually but not always valid) assumptions about the nature of your objects. If those are wrong, DI may not be the best solution: First, most basically, DI assumes that tight coupling of object implementations is ALWAYS bad.
Dependency Injection (DI) is a programming technique that makes a class independent of its dependencies. Creating objects directly within the class is inflexible because it commits the class to particular objects and makes it impossible to change the instantiation later independently from the class.
If you have a really small project with 12 classes, then a DI framework is almost certainly overkill. As a rule of thumb, the point where it becomes truly useful is when you find yourself repeatedly writing code that wires up object graphs with multiple dependencies and have to think about where to put that code.
When injecting your dependencies without a DI framework you end up with arrow code all over your application telling classes how to build their dependencies.
public Contact()
: this(new DataGateWay())
{
}
But if you use something like Ninject, all the arrow code is in one spot making it easier to change a dependency for all the classes using it.
internal class ProductionModule : StandardModule
{
public override void Load()
{
Bind<IDataGateway>().To<DataGateWay>();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With