Are controllers necessary when using Ninject in ASP.NET mvc 4

I don't understand what to do with a lot of documentation available via google in .net regarding using Ninject with asp.net mvc 4

First of all, I want to know if controllers are needed in asp.net.

In addition, constructor injection is indeed the only way we can do dependency injection with MVC 4, because property injection and method injection do not work when I use them with my controllers.

+7
source share
2 answers

I am not a Ninject expert, but as far as I know, I use it only to reference my DataSource Interface and my EfDb Class to the rest of my application.

If you need a good book that has a real application built around Ninject , try: Pro ASP.NET MVC 3 Framework, third edition

or

Pro Asp.Net Mvc 4

There are very few lines of code that I usually relate to

 public class NinjectControllerFactory : DefaultControllerFactory { private IKernel ninjectKernel; public NinjectControllerFactory() { ninjectKernel = new StandardKernel(); AddBindings(); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return controllerType == null ? null : (IController) ninjectKernel.Get(controllerType); } private void AddBindings() { ninjectKernel.Bind<IDataSource>().To<EfDb>(); } } 

Then register your NinjectControllerFactory in Global.asax.cs with:

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

As you can see, this class uses Method Injection using private void AddBindings() . This makes it very easy if you follow Test Driven Development (TDD)

+9
source

See the documentation here: https://github.com/ninject/ninject.web.mvc/wiki/Dependency-injection-for-controllers , "The only thing you need to do is set up Ninject bindings for your dependencies. The controller itself will find Ninject even without adding a binding. "

NInject automatically configures your dependencies between controllers (provided that they are bound to these types).

+2
source

All Articles