Thursday, January 29, 2015

Getting started with Ninject for ASP.NET MVC and ASP.NET Web API

If you are using ASP.NET MVC or ASP.NET Web API, you are probably interested in using a Dependency Injection Framework such as Ninject to help you with Unit Testing your Controllers.

Well, fortunately, getting started with Ninject in your ASP.NET MVC or ASP.NET Web API projects is relatively easy!

First, either create an ASP.NET MVC or ASP.NET Web API project.

Once you have done that, you will need to add NuGet packages to your project to add the Ninject reference assemblies.

For an ASP.NET MVC web application, you will want to add Ninject.MVC5 and ninject.extensions.conventions:

For an ASP.NET Web API project, you will want to add Ninject integration for WebApi 2 and ninject.extensions.conventions:

You will also have to add a NuGet package reference for WebActivator:

For your Web API project, the NinjectWebCommon.cs file will not automatically be added to your project, so you may have to copy and paste it from a sample ASP.NET MVC project.  The NinjectWebCommon.cs file should be placed in the App_Start folder of your ASP.NET MVC web application.

In the NinjectWebCommon.cs file in your project, you can then add your kernel.Bind code to inject all of the appropriate dependencies in the RegisterServices method.

That is all there is to it!!

No comments:

Post a Comment