gpt4 book ai didi

asp.net-core - 是否对在整个 ASP.NET Core 3 应用程序中使用完全相同的 HTTPContextAccessor 实例感到困惑?

转载 作者:行者123 更新时间:2023-12-04 16:02:01 24 4
gpt4 key购买 nike

我读过关于配置 IHttpContextAccessorservices.AddSingleton范围,但我也读到它正在“本地异步”工作,我也知道异步在 ASP.Net 中的复杂工作,我的意思是,例如,如果 Controller 操作方法是 async ,它await对于 async调用,然后它可能会继续使用另一个线程,但神奇的是一些线程绑定(bind)的东西与维护(如 HttpContext )

我的具体用例:我必须注入(inject)一个 MyConverter类(class)到我的 EF Core DbContextOnModelCreating 中使用它.但是,此模型由 DbContext 缓存,所以任何后续的请求,即使它会有一个全新的 DbContext 实例将使用这个非常相同的模型,所以非常相同 MyConverter实例。 (即使它已经配置了 services.AddTransient )。此 MyConverter有一个构造函数和一个注入(inject)的 IHttpContextAccessor ,因此基于非常相似的原因,它实际上也是所有 DbContext/MyConverter 的单例。用法。

问题

这个特别HttpContextAccessor在第一个请求中创建的实例将为 Web 应用程序生命周期中的所有后续请求提供服务。它会正常工作吗?这里有任何(并发)陷阱吗?

(我是否正确地认为 并不重要 如果我们使用单个或多个 HttpContextAccessor 实例,因为它获取 HttpContext 的实现将使用正确的方法,包括异步本地线程切换陷阱等返回正确的 HttpContext?)

最佳答案

简短回答:注册为 services.AddHttpContextAccessor()然后你可以注入(inject)IHttpContextAccessor只要你在请求的执行上下文中使用它,它就会在任何你想要的地方工作。例如,您无法读取不是由 HTTP 请求发起的代码的 HTTP 请求 header 。

你是对的 IHttpContextAccessor应该注册为单例。而不是自己做,recommendation是使用 AddHttpContextAccessor()扩展方法。见 source code here .它内部注册了一个 HttpContextAccessor作为单例。
HttpContextAccessor的代码can be found here ,我也在下面粘贴:

public class HttpContextAccessor : IHttpContextAccessor
{
private static AsyncLocal<HttpContextHolder> _httpContextCurrent = new AsyncLocal<HttpContextHolder>();

public HttpContext HttpContext
{
get
{
return _httpContextCurrent.Value?.Context;
}
set
{
var holder = _httpContextCurrent.Value;
if (holder != null)
{
// Clear current HttpContext trapped in the AsyncLocals, as its done.
holder.Context = null;
}

if (value != null)
{
// Use an object indirection to hold the HttpContext in the AsyncLocal,
// so it can be cleared in all ExecutionContexts when its cleared.
_httpContextCurrent.Value = new HttpContextHolder { Context = value };
}
}
}

private class HttpContextHolder
{
public HttpContext Context;
}
}

HttpContext getter 属性从异步本地字段返回,你总是得到 HttpContext本地到执行上下文。
HttpContext字段设置在 HttpContextFactory.Create()仅当 IHttpContextAccessor已在 DI 注册。 Source .

HttpContextFactory.Create()[HostingApplication](https://github.com/aspnet/AspNetCore/blob/v2.2.5/src/Hosting/Hosting/src/Internal/HostingApplication.cs) 调用设置上下文的位置。

关于asp.net-core - 是否对在整个 ASP.NET Core 3 应用程序中使用完全相同的 HTTPContextAccessor 实例感到困惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56286238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com