Dependency Injection with Ninject

plus IoC and other stuff!

Paul Zerkel

11/7/2013

What is Ninject?

Ninject is an open source dependency injection framework for the .NET platform. It is powerful but also designed to be easy enough to use on all projects.

What is Inversion of Control?

Inversion of Control (IoC) is an object oriented programming technique where collaborating objects work through abstractions and the implementation of those abstractions are not known at run-time.



IoC helps keep objects loosely coupled

Examples of IoC

  • Dependency Injection
  • Service Locator
  • Factory Pattern

What is Dependency Injection?

Dependency Injection is a form of Inversion of Control where an object receives required objects from an external source.

DI Example


public class TaskFinder
{
    private readonly ITaskService service;

    public TaskFinder(ITaskService service)
    {
        this.service = service;
    }
 
    public IEnumerable<WorkTask> Find(string email, int minPriority)
    {
        return service.FindTasks(email)
            .Where(x => x.Priority >= minPriority);
    }
}
					

This looks like a lot of extra work...

It would be, but that is where a DI framework will help.

How?

Ninject ...

  • Uses a fluent interface to bind types to what will implement them.
  • Manages the creation of objects and their dependencies.
  • Also manages the creation of dependencies and their dependencies (and so on).
  • Handles the lifetime of objects.

Binding Examples

  • Simple Binding
    
    Bind<ITaskService>().To<SimpleTaskService>();
    							
  • Binding with a constructor argument
    
    Bind<ITaskService>>().To<ExchangeService>()
                    .WithConstructorArgument("url",
                    new Uri("http://anotherserver.com"));
    							
  • Binding with context
    
    Bind<IRetryPolicy>().To<RandomRetryPolicy>().WhenInjectedInto<LoggingRetryPolicy>();
    							

Kernel

The Kernel allows you to retrieve objects that are fully constructed from Ninject.

Kernel Example


var taskFinder = kernel.Get<TaskFinder>();