21

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?

Arthur Rizzo
  • 1,337
  • 15
  • 30

1 Answers1

18

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.

Dai
  • 141,631
  • 28
  • 261
  • 374
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 2
    I dont understand this statement at all: " .NET Core is using a AsyncLocal which relies upon the instance variable to track the TLS storage slot". But the question was answered! thanks. – Arthur Rizzo Sep 20 '17 at 19:48
  • I totally disagree with this answer. async local should be avoided and request scope should be the clean and efficient way to go. See here for a simple and effective solution: https://stackoverflow.com/questions/49966858/scoped-service-access-http-context-without-ihttpcontextaccessor – Spi Oct 02 '18 at 08:21
  • "backing store is async local": is this mean, that the accessor will have a singleton instance by thread (plus handles correctly the thread switches what happen when request serving thread uses async an magically continues in an other thread?) – g.pickardou May 23 '19 at 16:55
  • 1
    The "later reply" is no longer valid https://github.com/dotnet/aspnetcore/commit/622d112372ed11075af160b1fb5a11a7637ff516#commitcomment-69899284 – kirodge Oct 19 '22 at 09:55