如何将依赖项注入到global.asax.cs中
如何将依赖项注入到 global.asax.cs(即 MvcApplication 类)中?
之前使用服务定位器(反)模式进行依赖注入,我尝试通过使用 IOC 容器(特别是 Unity.Mvc3,因为它附带了 IDependencyResolver 的实现)来遵循我最新的 MVC 应用程序中的最佳实践建议框)和构造函数注入。
到目前为止,除了一些障碍之外,一切似乎都很简单,其中一个是在 global.asax.cs 中(另一个是自定义属性,但已经有一个关于此的问题)。
MvcApplication 类中的 HttpApplication 事件处理程序,例如:
Application_Start()
Application_EndRequest(object sender, EventArgs e)
Application_AcquireRequestState(object sender, EventArgs e)
可能需要外部依赖项,例如对 ILogService 的依赖项。那么我如何注入它们而不诉诸服务定位器(反)模式,例如
private static ILogService LogService
{
get
{
return DependencyResolver.Current.GetService<ILogService>();
}
}
任何帮助/建议,非常感谢!
How do I inject dependencies into the global.asax.cs, i.e. the MvcApplication class?
Having previously used the Service Locator (anti-)pattern for dependency injection, I am trying to follow best practice advice in my latest MVC application by using an IOC container (specifically Unity.Mvc3 because it comes with an implementation of the IDependencyResolver out of the box) and constructor injection.
Everything seems quite straight forward so far except for a couple of snags, one of which is in the global.asax.cs (the other is for custom attributes but there's aleady a question on SO covering that).
The HttpApplication event handlers in the MvcApplication class such as:
Application_Start()
Application_EndRequest(object sender, EventArgs e)
Application_AcquireRequestState(object sender, EventArgs e)
may require external dependencies, e.g. a dependency on an ILogService. So how do I inject them without resorting to the service locator (anti-)pattern of e.g.
private static ILogService LogService
{
get
{
return DependencyResolver.Current.GetService<ILogService>();
}
}
Any help/advice greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
global.asax.cs 中的类是您的 Composition Root,因此你不能(也不应该)从外部向其中注入任何东西。
但是,MvcApplication 类只有一个实例,因此如果您需要在其方法之一中使用服务,只需将其声明为成员字段 - 例如:
The class in your global.asax.cs is your Composition Root, so you can't (and shouldn't) inject anything into it from the outside.
However, there's only one instance of the MvcApplication class, so if you need a service in one of its methods, you can just declare it as a member field - e.g:
您必须使用
AutofacConfig.Resolve()
而不是使用DependencyResolver.Current.GetService()
才能正确获取服务。You must use
AutofacConfig.Resolve<T>()
instead usingDependencyResolver.Current.GetService<T>()
to get your services without errors.