Click here to Skip to main content
11,803,019 members (80,116 online)
Click here to Skip to main content

Dependency Injection in mvc4 and webapi using Ninject

, 28 Jun 2012 CPOL 92.8K 33
Rate this:
Please Sign up or sign in to vote.
After using in for long, I was looking for a simple, fast and no xml Dependency Injector. For an mvc4 application I finally settled on Ninject because of its no xml approach, simplicity and ease of use. So, how to choose a Dependency Injector?, well every Dependency Inject

After using in for long, I was looking for a simple, fast and no xml Dependency Injector. For an ASP.NET MVC4 application I finally settled on Ninject because of its no XML approach, simplicity and ease of use.

So, how to choose a Dependency Injector? Well every Dependency Injector has its strengths and weaknesses and comes with a different feature set. Choosing Dependency Injector is a matter of evaluation and what you expect out of it.

Ninject is an open source Dependency Injector for .NET, created by Nate Kohari, and it comes with good set of extension and one of them is extension for ASP.NET MVC3.

Anyways, like me if you also like to try new and promising stuff, you will like to use Ninject , you can read more about Ninject on

Why Dependency Injection?

There are several benefits of using dependency injection rather than having components satisfy their own dependencies. Some of these benefits are:

  • Reduced boiler plate code and dependency carrying, flexibility to use alternative implementation of a given service without recompiling the application code.
  • Loose coupling between classes by promoting use of interfaces
  • Code becomes more reusable, testable and readable. If you are new to DI you can read more.

What do we Need to Integrate Ninject in ASP.NET MVC4?

Download Ninject and its ASP.NET MVC3 extension (there is no extension for ASP.NET MVC4 yet)

How to integrate Ninject in ASP.NET MVC4?

  • Add Ninject Dependencies to the project. You need to add reference to following DLLs in your ASP.NET MVC4 project
  1. Ninject.dll
  2. Ninject.Web.Common.dll
  3. Ninject.Web.Mvc.dll
  • Modify controller code to declare a read-only member variable of your service and modify the constructor to introduce the service instance parameter as below:
8.namespace NinjectMvc4.Controllers
10.    public class HomeController : Controller
11.    {
12.        private readonly IMessageService _messageService;
13.        public HomeController(IMessageService  messageService)
14.        {
15.            _messageService = messageService;
16.        }
18.        public ActionResult Index()
19.        {
20.            ViewBag.Message = _messageService.GetWelcomeMessage();
21.            return View();
22.        }
24.    }

I have IMesssageService interface and want to inject _messageService with the implementation MessageService using Ninject.

6.namespace NinjectMvc4.ServiceLayer
8.    public class MessageService:IMessageService
9.    {
10.        public string GetWelcomeMessage()
11.        {
12.            return "Welcome to Ninject MVC4 Example";
13.        }
14.    }
  • Modify Global.asax, Inherit  MvcApplication class from abstract class NinjectHttpApplication which is part of Ninject.Web.Common namespace.
  • Implement CreateKernel Method as follows: Create instance of StandardKernel, Load Executing assembly using the kernel , Bind Service Interface with the implementation to be injected.
  • In this example, while constructing the controllers this will inject the MessageService instance inside HomeController’s constructor so that it can be assigned to _messageService member variable.
14.namespace NinjectMvc4
 16.    public class MvcApplication : NinjectHttpApplication
 17.    {
 18.        protected override IKernel CreateKernel()
 19.        {
 20.            var kernel = new StandardKernel();
 21.            kernel.Load(Assembly.GetExecutingAssembly());
 22.            kernel.Bind<IMessageService>().To<MessageService>();
 23.            return kernel;
 24.        }
 25.        protected override void OnApplicationStarted()
 26.        {
 27.            base.OnApplicationStarted();
 28.            AreaRegistration.RegisterAllAreas();
 29.            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 30.            RouteConfig.RegisterRoutes(RouteTable.Routes);
 31.            BundleConfig.RegisterBundles(BundleTable.Bundles);
 32.        }
 33.    }

Override OnApplicationStarted to Register Filters, routes and bundles etc. (standard ASP.NET MVC4 stuff which we used to do in Application_Start event when not using ninject)

Cool, you are done, lets run the application and see that welcome message is now coming from the MessageService, which got injected into the HomeController.


Ninject is now integrated with asp.netMvc4, no different than the approach used to integrate it with ASP.NET MVC3.

If you want to integrate it with webapi, (injecting into apicontrollers) using DependencyResolver approach
Just implement System.Web.Http.Dependencies.IDependencyResolver at your own.

Why? Because currently Ninject’s Dependency Resolver comes with implementation of System.Web.Mvc.IDependencyResolver which cannot be assigned to GlobalConfiguration.Configuration of WebApi Application, it expects an instance of System.Web.Http.Dependencies.IDependencyResolver instead of System.Web.Mvc.IDependencyResolver , read more about this.

86. public class LocalNinjectDependencyResolver :
87.    {
88.        private readonly IKernel _kernel;
90.        public LocalNinjectDependencyResolver(IKernel kernel)
91.        {
92.            _kernel = kernel;
93.        }
94.        public System.Web.Http.Dependencies.IDependencyScope BeginScope()
95.        {
96.            return this;
97.        }
99.        public object GetService(Type serviceType)
100.        {
101.            return _kernel.TryGet(serviceType);
102.        }
104.        public IEnumerable<object> GetServices(Type serviceType)
105.        {
106.            try
107.            {
108.                return _kernel.GetAll(serviceType);
109.            }
110.            catch (Exception)
111.            {
112.                return new List<object>();
113.            }
114.        }
116.        public void Dispose()
117.        {
118.            // When BeginScope returns 'this', the Dispose method must be a no-op.
119.        }
120.   }

And modify the CreateKernel Method as below to assign an instance of LocalNinjectDependencyResolver to GlobalConfiguration.

protected override IKernel CreateKernel()
 46.        {
 47.            var kernel = new StandardKernel();
 48.            kernel.Load(Assembly.GetExecutingAssembly());
 49.            GlobalConfiguration.Configuration.DependencyResolver = new LocalNinjectDependencyResolver(kernel); 
 50.            return kernel;
 51.        }

That’s it, we can live with this work around for now. Please click here if you need to download the sample source code.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

I started programming for fun when I was in Higher Secondary (1995). It was a table writing program in C..haah!! those were the best days of my life Smile | :)

But now it has brought me to no. of jobs in roles of developer, Lead, Architect, Coach and Consultant....

.Net c# is my passion specially when it comes to build api and frameworks to facilitates development teams....

I always learned things by example, now its a pleasure and responsiblity to give learnings back to next generation of coders.

You may also be interested in...

Comments and Discussions

QuestionThanks Pin
Mohit-CleverCues2-Nov-14 19:19
memberMohit-CleverCues2-Nov-14 19:19 
GeneralMy vote of 1 Pin
Member 987805019-Aug-14 23:19
memberMember 987805019-Aug-14 23:19 
GeneralMy vote of 1 Pin
prageeth.madhu2-Jul-14 7:21
memberprageeth.madhu2-Jul-14 7:21 
General[My vote of 1] Poor Pin
Member 939452516-Jun-14 0:28
memberMember 939452516-Jun-14 0:28 
GeneralMy vote of 3 Pin
GregoryW1-Sep-13 21:50
memberGregoryW1-Sep-13 21:50 
QuestionParameter root Pin
Akinlaja Solomon Adebayo27-Aug-13 6:02
memberAkinlaja Solomon Adebayo27-Aug-13 6:02 
GeneralMy vote of 5 Pin
Glyn Lewis6-May-13 16:33
memberGlyn Lewis6-May-13 16:33 
GeneralMy vote of 3 Pin
GregoryW27-Apr-13 22:45
memberGregoryW27-Apr-13 22:45 
Questionwhy doesn't work? Pin
Stoica Constantin22-Feb-13 4:25
memberStoica Constantin22-Feb-13 4:25 
QuestionDon't Work Pin
Stoica Constantin12-Feb-13 2:44
memberStoica Constantin12-Feb-13 2:44 
QuestionDo you have an example using Ninject+WebApi Pin
JoseRoj24-Jan-13 5:56
memberJoseRoj24-Jan-13 5:56 
GeneralMy vote of 5 Pin
Shubha_India8-Jan-13 7:47
memberShubha_India8-Jan-13 7:47 
GeneralVery useful article Pin
PraveenKumarReddyChinta3-Dec-12 3:10
memberPraveenKumarReddyChinta3-Dec-12 3:10 
GeneralMy vote of 1 Pin
Erik Funkenbusch25-Oct-12 20:53
memberErik Funkenbusch25-Oct-12 20:53 
BugDON'T amend global.asax if you use NuGet!! Pin
BobHicks28-Aug-12 10:35
memberBobHicks28-Aug-12 10:35 
GeneralRe: DON'T amend global.asax if you use NuGet!! Pin
pmorrisweb22-Jan-13 2:14
memberpmorrisweb22-Jan-13 2:14 
Generaldefinition not found FilterConfig Pin
dfwzh6-Aug-12 19:28
memberdfwzh6-Aug-12 19:28 
QuestionDo you see any benefits over and above IUnityContainer? Pin
varun_manipal28-Jun-12 9:42
membervarun_manipal28-Jun-12 9:42 
AnswerRe: Do you see any benefits over and above IUnityContainer? Pin
ring_06-Jul-12 4:18
memberring_06-Jul-12 4:18 
GeneralRe: Do you see any benefits over and above IUnityContainer? Pin
Bhupindra Singh6-Jul-12 6:47
memberBhupindra Singh6-Jul-12 6:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151002.1 | Last Updated 28 Jun 2012
Article Copyright 2012 by Bhupindra Singh
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid