Dependency Injection with Ninject in .NET

Hello All

From last few months I was not working on .NET platform so haven’t get enough time to write something fruitful on .NET technology. But from last few few days I was thinking to do something with IoC . There are many DI tools to perform DI in .NET but I found Ninject useful as well as light waited and easily implementable. So lets start to make our hand dirty with the Ninject (there are many advanced level use of Ninject library but in this article I will simply show how to do DI with Ninject framework).

My project structure is as following .

In this example I’m taking 2 types of engine and 2 types of set and through Ninject DI I’ll inject one of each for a car. Fore the sake of simplicity I will place the code file accordingly and describe through code comment.

In my “DependencyInjection.Core” project I took 2 interfaces: 1.IEngine  2.ISeat

IEngine.cs is as following :

I’m also taking 2 other classes 1.DieselEngine and 2.PetrolEngine  . Both of the classes implements IEngine interface.

DieselEngine.cs is as following :

PetrolEngine.cs is as following :

Now start for another type of interface implementation ISeat . This part also is as above.

ISeat.cs is as following :

Two other classes 1.LeatherSeat and 2.PlasticSeat  . Both of the classes implements ISeat interface.

LeatherSeat.cs is as follwong:

PlasticSeat.cs is as following :

In this point I’m adding reference of “Ninject.Core.dll” with my  “DependencyInjection.Core” project which I have downloaded from Ninject’s site. Now in my main class “Car” I’m going to inject one type of engine and another type of seat which I have mapped (DI mapping) through “IocMapper” class as bellow.

Car.cs is as bellow :

In the above file  “ [Inject] “ attribute is place above the Car constructer to make it definable to Ninject so that Ninject can inject mapped object as described in “IocMapper” class.

I have taken another console application project named “DependencyInjection” in which I placed my “IocMapper” class.

IocMapper.cs is as following :

Now in program class I defined the kernel constructer and and initialize my car object.

Program.cs file is as bellow :

We can do more advance level of conditional binding with Ninject. Hope in near future I will throw a post on advance use of Ninject.

That’s all for today.

BYE