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:
- Install the NuGet package
Install-Package Ninject
- Create a module
- Create a kernel
- 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!
This is a great short tutorial, thank you for sharing Adam.