为什么我应该将 IHttpContextAccessor 作为单例注入
Why should I inject IHttpContextAccessor as a Singleton
在我见过的所有 IHttpContextAccessor
注入示例中,它都被设置为 Singleton。
示例:
我觉得有点奇怪,因为 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.
在我见过的所有 IHttpContextAccessor
注入示例中,它都被设置为 Singleton。
示例:
我觉得有点奇怪,因为 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.