Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Ninject create controller in ASP.NET MVC?

This may be stupid question, but I am looking at Ninject sources and don't see NInject registering its own controller factory. I also don't see any IControllerFactory class in Ninject.Web.Mvc assembly. Am I missing something? How does Ninject create controller and inject parameters into constructor?

like image 810
LukLed Avatar asked Feb 16 '11 16:02

LukLed


2 Answers

  1. Lets say we are looking for "/Task/Index".
  2. Ninject MVC applications use now DefaultControllerFactory, the same as non-Ninject applications.
  3. DefaultControllerFactory finds type for controller (TaskController).
  4. DefaultControllerFactory has internal class called DefaultControllerActivator. DefaultControllerActivator has method called Create, which returns controller instance. DefaultControllerFactory asks DefaultControllerActivator for TaskController type instance.
  5. DefaultControllerActivator.Create uses IDependencyResolver. This is where Ninject comes in. Since Ninject implements its own resolver and sets it at the start of application, he gets request for TaskController instance.
  6. The rest is easy. Ninject finds constructor for this type, injects parameters, returns controller instance.
like image 177
LukLed Avatar answered Oct 12 '22 17:10

LukLed


MVC3 now recommends the usage of the IDependencyResolver interface instead of the good old IControllerFactory when dealing with DI. You can look at more details of this interface here.

This is the new Ninject class responsible for injecting the dependencies.

like image 43
goenning Avatar answered Oct 12 '22 16:10

goenning