IHttpContextAccessor Performance

Posted September 5, 2023 in asp.net-core httpcontext ihttpcontextaccessor performance
Reading time: 1 minute

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 IHttpContextAccessor?

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 IHttpContextAccessor.

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.



Comments

comments powered by Disqus