Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection Frameworks: Why do I care?

I was reading over Injection by Hand and Ninjection (as well as Why use Ninject ). I encountered two pieces of confusion:

  1. 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

  2. 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.

like image 856
Brian Avatar asked Jun 04 '09 18:06

Brian


People also ask

Why should I use a dependency injection framework?

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).

Why we should not use dependency injection?

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.

How do you explain dependency injection?

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.

Is dependency injection an overkill?

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.


1 Answers

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>();
    }
}
like image 163
Aaron Avatar answered Sep 24 '22 23:09

Aaron