Wednesday, February 15, 2012

Ninject and Visual Studio 2010

         Ninject is an open source DI container for .Net. I would like to briefly introduce how to use it in VS2010.
         It can be easily added to your project's reference by VS2010's "Add Package Library Reference" feature. The detail steps are:
  1. Right-click your project in Solution Explorer, select  "Add Package Library Reference" from popup menu.
  2. In the  "Add Package Library Reference" dialog, click "Online" on left pane, then type "Ninject" in the search field at the top right corner.
  3. Select "Ninject" (this is the core Ninject component) and click "Install".
         Ninject library should show up in the References list now.

         There are 3 steps to use Ninject in your code (I use the classes defined in my previous blog):

     1. Create an instance of Ninject kernel.

          IKernel kernel = new StandardKernel();

     2. Bind a interface to a class that implements that interface.

         kernel .Bind<IVehicle>().To<Car>();

     3. Create and use the instance has the interface implementation.

         // get the interface implementation using Get method of Ninject kernel
         IVehicle vehicleImpl = kernel .Get<IVehicle>();

         // create the instance of Man and inject the dependency
         Man men = new Man (vehicleImpl);

         // perform the car.drive() method
         men.drive();

No comments: