Arthur Rizzo Arthur Rizzo - 5 months ago 68
C# Question

Why should I inject IHttpContextAccessor as a Singleton

In all examples that i've seen of

injection, it is set as a 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

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

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

Answer Source

Is Singleton really the recomended way?


According to comments associated with an issue raised on GitHub

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

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 TLS storage slot. So it has to be registered as a singleton on .NET Core.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download