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

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

概述这是运行.Net 3.5的 Asp.net应用程序(不是MVC) 我这样做了: protected void Application_Start(object sender, EventArgs e) { ... builder.Register(c => new HttpContextWrapper(HttpContext.Current)) .As<H 这是运行.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,并查看问题是否仍然存在.如果是这样,弄清楚哪个是单件组件应该相当简单.

总结

以上是内存溢出为你收集整理的c# – 如何在Asp.Net(非MVC)中使用Autofac注册HttpContextBase全部内容,希望文章能够帮你解决c# – 如何在Asp.Net(非MVC)中使用Autofac注册HttpContextBase所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1243736.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存