c# – 如何在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); } } 我得到了一个N??ull Reference Exception. 奇怪的是,context.Response不是null,当我调用它时抛出的.Redirect(). 我想知道是否使用.InstancePerLifetimeScope();是问题. 顺便说一句,我尝试使用Response.Redirect(),它完美无缺. 那可能是什么问题呢? 谢谢, 驰 解决方法
看起来您的HttpService类可能被注册为SingleInstance()(单例)组件.或者,其中一个将IHttpService作为依赖项的类是单例.
发生这种情况时,即使您已设置Autofac以返回每个HTTP请求(或生命周期范围,这也是正确的)新的HttpContextBase实例,HttpService类将挂起到创建单个HttpService实例时当前的HttpContextBase. 要测试此理论,请尝试直接从页面依赖HttpContextBase,并查看问题是否仍然存在.如果是这样,弄清楚哪个是单件组件应该相当简单. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |