如何在Asp.Net(不MVC)与Autofac注册Htt​​pContextBase [英] How to register HttpContextBase with Autofac in Asp.Net (not MVC)

查看:176
本文介绍了如何在Asp.Net(不MVC)与Autofac注册Htt​​pContextBase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is a Asp.net application (not MVC) running .Net 3.5

我这样做:

 protected void Application_Start(object sender, EventArgs e)
 {

 ...

       builder.Register(c => new HttpContextWrapper(HttpContext.Current))
          .As<HttpContextBase>()
          .InstancePerHttpRequest();
 }

但它不工作。

我得到这个错误:

否与标记匹配的'HTT prequest'的范围是其中要求该实例的范围可见。这通常表示登记为每个HTTP请求的组件是由一个SingleInstance()成分reqested(或类似的情形。)在幅积分总是请求从DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime依赖关系,不会从容器本身

于是我发现了这个: http://stackoverflow.com/a/7821781/305469

和我这样做,而不是:

       builder.Register(c => new HttpContextWrapper(HttpContext.Current))
          .As<HttpContextBase>()
          .InstancePerLifetimeScope();

但现在当我这样做:

But now when I do this:

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);
    }
}

和我有一个空引用异常。

and I got a Null Reference Exception.

奇怪的是,context.Response不为空,这是当我打电话.Redirect(),它抛出。

Strangely, context.Response is not null, it is when I call .Redirect() that it throw.

我如果用.InstancePerLifetimeScope()不知道;就是问题所在。

I am wondering if using .InstancePerLifetimeScope(); is the problem.

BTW,我尝试使用的Response.Redirect()和它完美的作品。

BTW, I tried using Response.Redirect() and it works perfectly.

那么,什么可能是问题?

So what could be the problem?

谢谢,

推荐答案

看起来好像你的 HttpService的类可以被注册为 SingleInstance( )(单身)的组成部分。或者,具有类之一 IHttpService 作为一个依赖是一个单例。

It looks as though your HttpService class may be registered as a SingleInstance() (singleton) component. Or, one of the classes that has IHttpService as a dependency is a singleton.

当这种情况发生时,即使你已经设置了Autofac返回一个新的 HttpContextBase 实例每个HTTP请求(或终生范围,这也是正确的)的 HttpService的类将挂在任何 HttpContextBase 是当前当单 HttpService的实例被创建。

When this occurs, even though you've set up Autofac to return a new HttpContextBase instance per HTTP request (or lifetime scope, which is also correct) the HttpService class will hang on to whichever HttpContextBase was current when the single HttpService instance was created.

要验证这一理论,尝试从页面上取 HttpContextBase 的依赖直接,看看问题是否仍然出现。搞清楚这是单独组件应该是相当简单,如果左右。

To test this theory, try taking a dependency on HttpContextBase directly from a page, and see whether the problem still occurs. Figuring out which is the singleton component should be fairly straightforward if so.

这篇关于如何在Asp.Net(不MVC)与Autofac注册Htt​​pContextBase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆