Why should I inject IHttpContextAccessor as a Singleton

瘦欲@ 提交于 2021-02-07 11:27:17

问题


In all examples that i've seen of IHttpContextAccessor injection, it is set as a Singleton.

Examples:

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

I find it kinda weird, since HttpContext really looks like something that maps to requests. Wouldn't AddScoped be more appropriate in this case?

Is Singleton really the recomended way? Am I not seeeing something?


回答1:


Is Singleton really the recomended way?

Yes

According to comments associated with an issue raised on 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?

It's fine being a singleton because the backing store is async local.

Which got a later reply

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.



来源:https://stackoverflow.com/questions/46330007/why-should-i-inject-ihttpcontextaccessor-as-a-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!