asp.net-core - 无法获取当前 http 请求的范围(Autofac 4)?

标签 asp.net-core autofac asp.net-core-mvc

当 HttpContext 存在时,如何获取当前 http 请求的 ILifetimeScope ?例如。我想通过静态扩展方法解析服务。我不想通过 BeginLifetimeScope() 方法创建新的作用域实例。

我花了几个小时但没有找到解决方案..

最佳答案

注意:这最初被交叉发布为 issue/question on Autofac那里有更多的背景。

根据 Autofac 问题中发布的代码,您基本上已经有了对应用程序容器的引用,您可以解析 IHttpContextAccessor ,从那里您可以获得当前的 HttpContext 。从那里您想要解决请求级服务并且陷入困境。

首先,需要注意的是,ASP.NET Core 的一个关键区别是它处理请求范围创建,而不是 Autofac。事实上,ASP.NET Core 几乎可以处理所有事情如发起服务解析等。 Autofac 支持 DI 容器接口(interface),但驱动 Autofac 调用的引擎(包括请求范围的创建和存储)全部是 ASP.NET Core。 (您可以看到in the ASP.NET "Hosting" repo where this happens.)。

了解这一点后,它可以帮助解决此类问题 - 您将知道不要查看 Autofac 代码,而是在 ASP.NET Core 中查找内容。

您会注意到在 ASP.NET Core 上 HttpContext there is a property RequestServices 。该属性是 ASP.NET Core 的请求生命周期范围。因此,如果您需要对 HttpContext 中的服务进行简单解析。 ,您可以使用它:

var accessor = _container.Resolve<IHttpContextAccessor>();
var context = accessor.HttpContext;
var resolved = context.RequestServices.GetService<MyService>();

如果您绝对必须具有特定于 Autofac 的请求生命周期范围,则可以解析 ILifetimeScope来自请求服务。您始终可以从范围/容器解析当前生命周期范围,因此您获得的范围将是请求范围。

var accessor = _container.Resolve<IHttpContextAccessor>();
var context = accessor.HttpContext;
var scope = context.RequestServices.GetService<ILifetimeScope>();
var resolved = scope.Resolve<MyService>();

关于asp.net-core - 无法获取当前 http 请求的范围(Autofac 4)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37891598/

相关文章:

c# - 如何从xamarin表单应用程序将图像上传到服务器

autofac - 使用 AutoFac 手动调用属性注入(inject)

asp.net-core - 使用路由参数读取 Asp.Net Core MVC 操作中的原始 Request.Body

c# - 如何在 EF Core 中查询多对多关系

c# - 在 ASP.NET Core 2.1 中使用 System.Text.Json 作为默认序列化器

c# - 如何使用工厂使用 Autofac 解析接口(interface)

asp.net - 找不到的构造函数都不能用可用的服务和参数 Autofac 调用

node.js - ASP.NET Core MVC 项目中的 node_modules 文件夹

c# - ArgumentException : The key value at position 0 of the call to 'DbSet<News>.Find' was of type 'string' , 与 int 的属性类型不匹配'

asp.net-core - openid connect - 登录期间识别租户