How does Ninject create controller in ASP.NET MVC?

断了今生、忘了曾经 提交于 2020-01-10 18:24:46

问题


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?


回答1:


  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.



回答2:


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.




回答3:


Since controllers are concrete types, Ninject will do self bind. Below is a snippet from ninject.complex.com

Bear in mind that only concrete types can be self-bound; abstract types and interfaces won't work. Also, if you request an instance of a type that can be self-bound, and there are no bindings defined for the type, Ninject will automatically create an implicit self-binding. It's up to you whether you want to define your bindings explicitly, or let Ninject figure it out.

If you do need to inject parameters into the constructor. You can create a class inherits from INinjectModule and do the binding there.



来源:https://stackoverflow.com/questions/5018810/how-does-ninject-create-controller-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!