这是运行.Net 3.5的Asp.net应用程序(不是MVC)
我这样做了:
protected void Application_Start(object sender, EventArgs e)
{
...
builder.Register(c => new HttpContextWrapper(HttpContext.Current))
.As<HttpContextBase>()
.InstancePerHttpRequest();
}
但它不起作用。
我得到的错误:
从请求实例的作用域中看不到具有匹配'httpRequest'的标记的作用域。这通常表示注册为每HTTP请求的组件正被SingleInstance()组件(或类似场景)重新请求。在Web集成下,始终从DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime请求依赖项,从不从容器本身请求
然后我发现了这个:https://stackoverflow.com/a/7821781/305469
而我这样做了:
builder.Register(c => new HttpContextWrapper(HttpContext.Current))
.As<HttpContextBase>()
.InstancePerLifetimeScope();
但现在我这样做了:
public class HttpService : IHttpService
{
private readonly HttpContextBase context;
public HttpService(HttpContextBase context)
{
this.context = context;
}
public void ResponseRedirect(string url)
{
//Throws null ref exception
context.Response.Redirect(url);
}
}
我得到了一个Null Reference Exception。
奇怪的是,context.Response不为null,它是在我调用.Redirect()时抛出的。
我想知道是否使用.InstancePerLifetimeScope();是问题。
BTW,我尝试使用Response.Redirect(),它完美无缺。
那可能是什么问题?
谢谢,
志
答案 0 :(得分:4)
您的HttpService
类似乎可以注册为SingleInstance()
(单例)组件。或者,其中一个以IHttpService
作为依赖项的类是单例。
发生这种情况时,即使您已设置Autofac以返回每个HTTP请求的新HttpContextBase
实例(或生命周期范围,这也是正确的),HttpService
类将挂起到哪个单HttpContextBase
个实例创建后,HttpService
是最新的。
要测试此理论,请尝试直接从页面依赖HttpContextBase
,并查看问题是否仍然存在。如果是这样的话,弄清楚哪个是单件组件应该相当简单。
答案 1 :(得分:0)
使用生命周期范围注册HttpContextWrapper就像使用RegisterInstance(),也就是说,您将始终使用相同的HttContextWrapper实例。因此,第二个请求将使用第一个请求的HttpContext,从而导致一些奇怪的错误。
可能的解决方法:为HttpContext创建自己的包装器并使用实例生命周期注册它并让它在内部使用当前的HttpContext:
public interface IMyWrapper
{
void ResponseRedirect(string url);
}
public class MyWrapper : IMyWrapper
{
public void ResponseRedirect(string url)
{
HttpContext.Current.Response.Redirect(url);
}
}
builder.Register(c => new MyWrapper())
.As<IWrapper>()
.InstancePerLifetimeScope();
但是这样就不会注入HttpContext了。不确定这是否重要......