Brian Brian - 1 year ago 42
C# Question

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.


Answer Source

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>();
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download