gpt4 book ai didi

c# - 为什么我应该将 IHttpContextAccessor 作为单例注入(inject)

转载 作者:太空狗 更新时间:2023-10-29 17:51:34 26 4
gpt4 key购买 nike

在我见过的所有 IHttpContextAccessor 注入(inject)示例中,它都被设置为 Singleton。

例子:

How to add IHttpContextAccessor in the Startup class in the DI in ASP.NET Core 1.0? Injecting IHttpContextAccessor into ApplicationDbContext ASP.NET Core 1.0 .NET Core IHttpContextAccessor issue

我觉得它有点奇怪,因为 HttpContext 看起来真的像是映射到请求的东西。在这种情况下 AddScoped 不是更合适吗?

Singleton 真的是推荐的方式吗?我没看到什么吗?

最佳答案

Is Singleton really the recomended way?

根据与 GitHub 上提出的问题相关的评论

https://github.com/aspnet/Hosting/issues/793#issuecomment-224828588

In that sample, you are registering it as a singleton. Shouldn't it be a scoped instance?

作为单例很好,因为后备存储是异步本地的。

得到了后来的回复

https://github.com/aspnet/Hosting/issues/793#issuecomment-224924030

Actually if you register it as a Transient on .NET Core then it doesn't work properly since the implementation for .NET Core is using a AsyncLocal which relies upon the instance variable to track the thread local storage slot. So it has to be registered as a singleton on .NET Core.

关于c# - 为什么我应该将 IHttpContextAccessor 作为单例注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46330007/

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