繁体   English   中英

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

[英]How to register HttpContextBase with Autofac in Asp.Net (not MVC)

这是一个运行.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);
    }
}

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

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

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

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

那可能是什么问题呢?

谢谢,

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

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

要测试此理论,请尝试直接从页面依赖HttpContextBase ,并查看问题是否仍然存在。 如果是这样的话,弄清楚哪个是单件组件应该相当简单。

使用生命周期范围注册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了。 不确定这是否重要......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM