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

这是运行.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。 不知道这是否重要...

链接地址: http://www.djcxy.com/p/59825.html

上一篇: How to register HttpContextBase with Autofac in Asp.Net (not MVC)

下一篇: Strange vertical line at side of emacs window, while it maximized