In my ASP.NET Core applications, I have a few scoped services that require an
HttpContext, but that don’t
have a way to directly pass the context as a method parameter. In these cases, the docs
say to inject
IHttpContextAccessor into your classes. However, if you read the API docs for
IHttpContextAccessor, you see a big warning in the Remarks:
This interface should be used with caution. It relies on
AsyncLocal<T>which can have a negative performance impact on async calls.
That sounds bad. Should I avoid using
I was curious, so I started searching for answers, and I found a GitHub issue where someone had the same concerns.
In short, the recommendation is still to use
In response to the warning about
AsyncLocal<T> causing negative performance issues, Microsoft Distinguished Engineer David Fowler said this:
… it’s not significant enough to affect any real application, mostly microbenchmarks and our crazy benchmarks that eek every ounce of performance out of the stack.
So, in other words, it probably won’t be an issue. For me, that’s almost certainly the case. YMMV.
As always, benchmark benchmark benchmark.