c# – 如何在Asp.Net(非MVC)中使用Autofac注册HttpContextBase

前端之家收集整理的这篇文章主要介绍了c# – 如何在Asp.Net(非MVC)中使用Autofac注册HttpContextBase前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是运行.Net 3.5的 Asp.net应用程序(不是MVC)

我这样做了:

  1. protected void Application_Start(object sender,EventArgs e)
  2. {
  3.  
  4. ...
  5.  
  6. builder.Register(c => new HttpContextWrapper(HttpContext.Current))
  7. .As<HttpContextBase>()
  8. .InstancePerHttpRequest();
  9. }

但它不起作用.

我得到的错误

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

所以我发现了这个:@L_502_1@

而我这样做了:

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

但是现在当我这样做时:

  1. public class HttpService : IHttpService
  2. {
  3. private readonly HttpContextBase context;
  4.  
  5. public HttpService(HttpContextBase context)
  6. {
  7. this.context = context;
  8. }
  9.  
  10. public void ResponseRedirect(string url)
  11. {
  12. //Throws null ref exception
  13. context.Response.Redirect(url);
  14. }
  15. }

我得到了一个N​​ull Reference Exception.

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

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

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

那可能是什么问题呢?

谢谢,

解决方法

看起来您的HttpService类可能被注册为SingleInstance()(单例)组件.或者,其中一个将IHttpService作为依赖项的类是单例.

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

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

猜你在找的C#相关文章