Understanding dependency injection in less than 30 minutes

I’ve received a question:

Hey, I want to use dependency injection, because it is trendy. I would like to use Ninject. How should I proceed?

Dependency injection is not a framework

Ninject is a really cool framework. But please, do not mix that both up. Yes, Ninject is a framework for dependency injection. It makes the life easier. But it is only an DI container. You can achieve DI even without Ninject or any other IoC/DI container.

What dependency injection actually is

Let’s take a look at the following code example:

interface InterfaceA { }
interface InterfaceB { }
interface InterfaceC { }
interface InterfaceD { }

class ClassA : InterfaceA { }
class ClassB : InterfaceB 
{
    public ClassB(InterfaceA a) { }
}
class ClassC : InterfaceC 
{
    public ClassC(InterfaceA a) { }
}
class ClassD : InterfaceD 
{
    public ClassD(InterfaceA a) { }
}
class Context 
{
    public Context(InterfaceA a, InterfaceB b, InterfaceC c, InterfaceD d) { }
}

class Client 
{
    public Client()
    {
        InterfaceA a = new ClassA();
        InterfaceB b = new ClassB(a);
        InterfaceC c = new ClassC(a);
        InterfaceD d = new ClassD(a);
        var context = new Context(a, b, c, d);
    }
}

Is it dependency injection?

Actually it is.

It does not make a difference if I instantiate all classes manually or do it by using a framework.

Ninject (or any other DI framework) should always be used on the top most layer.

Let’s take a look on the onion pattern. The DI is always a part of the UI library. It does not matter what you are use. Tests, ASP.net, WPF, WinForms (does this really someone use?), MVVM, etc.

It even does not matter which framework (or not) you are use. Ninject, Windsor Castle, MEF, TinyIoC, etc.

Do not mix up dependency injection with a service locator

First of all, what is a service locator?

It is a container, where some instances are registered and can be resolved by a single call on another method.

class Client
{
    private IRepository _repository;
    public Client()
    {
        _repository = Kernel.Get<IRepository>();
    }
}

What will be happen, if there is no Repository registered? Exactly, the app will crash and the caller will not know why. He did everything right.

Mark Seemann described the service locator as an anti-pattern in more detail 🙂

Another issue is, that you need to use a DI container in your business code. What happen, if you ever decide to change the container?

Why do you need Ninject within a “AccountManager.dll”? This is actually an unneeded dependency (haha 🙂 ).

Conclusion

Dependency injection …

  • … is really cool
  • … does not belong on a framework
  • … is not a framework
  • … frameworks should only be used within the UI layer
  • Do not use something, because it’s trendy. Use it, because you need it!

Leave a Reply

Your email address will not be published.