The Way of the Ninject

In recent months, I’ve come to be a big fan of Ninject. I’ve used Microsoft’s Unity Container and Object Builder in the past, but most of what I’d done previously just involved exposing dependencies as properties with lazily-loaded default implementations. I really dig Ninject because it’s so lightweight and easy to use, and it integrates really well with mocking frameworks like Rhino Mocks and Moq.

Getting started with Ninject is really easy and accomplished in just a few steps:

  1. Install the NuGet package
    Install-Package Ninject
  2. Create a module
  3. Create a kernel
  4. Get objects from the kernel

Let’s look at an example. Assume we have the following interfaces and classes.

public interface IFoo {
    void Run();
}

public class Foo : IFoo {
    private readonly IBar _bar;

    public Foo(IBar bar) {
        _bar = bar;
    }

    public void Run() {
        _bar.Print();
    }
}

public interface IBar {
    void Print();
}

public class Bar : IBar {
    public void Print() {
        Console.WriteLine("Yay!");
    }
}

We can create a NinjectModule to create an instance of IFoo like this.

public class FooModule : NinjectModule {
    public override void Load() {
        Bind<IFoo>().To<Foo>();
        Bind<IBar>().To<Bar>();
    }
}

Now, we need to tell our Ninject kernel to use our new module.

IKernel kernel = new StandardKernel(
    new FooModule());

And, finally, we use the kernel to request the objects we need. Note that Ninject does the work of figuring out the default implementation of IFoo (Foo) has a single constructor that accepts a dependency, IBar, and that the default implementation of the dependency is Bar.

class Program {
    static void Main(string[] args) {
        IKernel kernel = new StandardKernel(
            new FooModule());
        IFoo foo = kernel.Get<IFoo>();
        foo.Run();
        Console.ReadLine();
    }
}

Output:

Yay!
Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

One thought on “The Way of the Ninject”

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: