如何在Asp.Net(而不是MVC)中使用Autofac注册HttpContextBase

Chi*_*han 7 c# asp.net autofac

这是一个运行.Net 3.5的Asp.net应用程序(不是MVC)

我这样做了:

 protected void Application_Start(object sender, EventArgs e)
 {

 ...

       builder.Register(c => new HttpContextWrapper(HttpContext.Current))
          .As<HttpContextBase>()
          .InstancePerHttpRequest();
 }
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

我得到的错误:

从请求实例的作用域中看不到具有匹配"httpRequest"的标记的作用域.这通常表示注册为每HTTP请求的组件正被SingleInstance()组件(或类似场景)重新请求.在Web集成下,始终从DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime请求依赖项,从不从容器本身请求.

所以我发现了这个:https://stackoverflow.com/a/7821781/305469

而我这样做了:

       builder.Register(c => new HttpContextWrapper(HttpContext.Current))
          .As<HttpContextBase>()
          .InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)

但是现在当我这样做时:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到了一个空参考例外.

奇怪的是,context.Response不是null,它是在我调用它时抛出的.Redirect().

我想知道是否使用.InstancePerLifetimeScope(); 是问题.

顺便说一下,我尝试使用Response.Redirect(),它完美无缺.

那可能是什么问题呢?

谢谢,

Nic*_*rdt 4

看起来您的HttpService类可能被注册为SingleInstance()(单例)组件。或者,具有依赖项的类之一IHttpService是单例。

发生这种情况时,即使您已将 Autofac 设置HttpContextBase为每个 HTTP 请求(或生命周期范围,这也是正确的)返回一个新实例,该类HttpService仍将保留在创建HttpContextBase单个实例时当前的实例。HttpService

要测试这个理论,请尝试直接从页面获取依赖项HttpContextBase,并查看问题是否仍然出现。如果是的话,找出哪个是单例组件应该相当简单。