autofac-依赖注入到IHttpModule中 [英] autofac - dependency injection into IHttpModule
问题描述
在IIS 7.5上使用autofac 3.0的新MVC 4 Web应用程序.如何将依赖项注入IHttpModule?
New MVC 4 web application using autofac 3.0 on IIS 7.5. How do I inject a dependency into an IHttpModule?
我尝试了构造函数注入,结果是:
I tried constructor injection which resulted in:
找不到类型为'AnonymousIdentityModule'的构造函数
Constructor on type 'AnonymousIdentityModule' not found
因此,似乎内部组件要求HTTP模块使用无参数的构造函数.我也尝试过属性注入,但是实际上没有注入依赖.
So it seems the internals require a parameterless constructor for http modules. I also tried property injection too but that resulted in no dependency actually being injected.
注册
builder.RegisterType<AnonymousIdentityModule>().As<IHttpModule>().PropertiesAutowired().InstancePerHttpRequest();
IHttpModule代码
public class AnonymousIdentityModule : IHttpModule
{
private readonly IServiceManager _serviceManager;
// this causes "constructor not found" exception
public AnonymousIdentityModule(IServiceManager serviceManager)
{
_serviceManager = serviceManager;
}
// never assigned by autofac
public IServiceManager ServiceManager
{
get { return _serviceManager; }
set { _serviceManager = value; }
}
...
}
web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="AnonymousIdentityModule" type="AnonymousIdentityModule" />
</modules>
</system.webServer>
我发现了这个旧的 文章 与温莎有关,但在autofac中却看不到它.
I found this old article related to Windsor but did not see an equivalent in autofac.
推荐答案
查看以下SO问题:以及Phil Haack的这篇文章:
and this post by Phil Haack: http://haacked.com/archive/2011/06/02/dependency-injection-with-asp-net-httpmodules.aspx
他们俩都在谈论通过创建另一个HttpModule来初始化DI来为HttpModules提供DI.如果需要的话,PH还提供了他的HttpModuleMagic的nuget包:
They both talk about providing DI to HttpModules by creating another HttpModule to initialize them. And PH has provided a nuget package of his HttpModuleMagic if you want it:
PM> Install-Package HttpModuleMagic
但是因为HttpModules仅在它们是一种单例之后才创建,并且您的依赖项也必须是一个单例(或更确切地说,是一个实例).
But because HttpModules are only created once they are a kind of singleton, and your dependency also has to be a singleton (or rather, a single instance).
So, if you need a per-request dependency, check out this post: http://blog.sapiensworks.com/post/2013/03/18/Http-Module-Dependecy-Injection-with-Autofac-Gotcha.aspx
这着眼于在需要时使用Factory函数检索适当范围的依赖项.
This looks at using a Factory function to retrieve a properly scoped dependency when needed.
这篇关于autofac-依赖注入到IHttpModule中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!