Ninject 如何在 ASP.NET MVC 中创建控制器?
这可能是一个愚蠢的问题,但我正在查看 Ninject 源代码,但没有看到 NInject 注册自己的控制器工厂。我在 Ninject.Web.Mvc
程序集中也没有看到任何 IControllerFactory
类。我错过了什么吗? Ninject 如何创建控制器并将参数注入构造函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于控制器是具体类型,Ninject 将进行自绑定。以下是来自
ninject.complex.com
的片段如果确实需要将参数注入到构造函数中。您可以创建一个继承自
INinjectModule
的类并在其中进行绑定。Since controllers are concrete types, Ninject will do self bind. Below is a snippet from
ninject.complex.com
If you do need to inject parameters into the constructor. You can create a class inherits from
INinjectModule
and do the binding there.DefaultControllerFactory
,与非 Ninject 应用程序相同。DefaultControllerFactory
查找控制器 (TaskController
) 的类型。DefaultControllerFactory
有一个名为DefaultControllerActivator
的内部类。DefaultControllerActivator
有一个名为Create
的方法,它返回控制器实例。DefaultControllerFactory
向DefaultControllerActivator
请求TaskController
类型实例。DefaultControllerActivator.Create
使用IDependencyResolver
。这就是Ninject
发挥作用的地方。由于Ninject
实现了自己的解析器并在应用程序启动时设置它,因此他收到对TaskController
实例的请求。Ninject
找到该类型的构造函数,注入参数,返回控制器实例。DefaultControllerFactory
, the same as non-Ninject applications.DefaultControllerFactory
finds type for controller (TaskController
).DefaultControllerFactory
has internal class calledDefaultControllerActivator
.DefaultControllerActivator
has method calledCreate
, which returns controller instance.DefaultControllerFactory
asksDefaultControllerActivator
forTaskController
type instance.DefaultControllerActivator.Create
usesIDependencyResolver
. This is whereNinject
comes in. SinceNinject
implements its own resolver and sets it at the start of application, he gets request forTaskController
instance.Ninject
finds constructor for this type, injects parameters, returns controller instance.MVC3 现在建议在处理 DI 时使用
IDependencyResolver
接口,而不是旧的IControllerFactory
接口。您可以在此处查看此接口的更多详细信息。这是新的 Ninject class 负责注入依赖项。
MVC3 now recommends the usage of the
IDependencyResolver
interface instead of the good oldIControllerFactory
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.