Search code examples
c#.net-coredependency-injectionhttpcontext

IHttpContextAccessor to get the jwt token singleton


I am using the IHttpContextAccessor to get the jwt token, my question would be in dependency injection.

Searching I see many people using singleton, how does IHttpContext handle multiple requests being singleton?

If the application is serving 3 or more requests with different tokens, each request thread will have its correct jwt even if the instance is unique?

services.AddScoped(x => new AuthToken(x.GetService<IHttpContextAccessor().HttpContext?.Request?.Headers["Authorization"]));


Solution

  • Take a look on AsyncLocal.

    It's how HttpContextAccessor is implemented, even being singleton it returns different values for different threads/requests. Answering your question, yes it's correct - Accessed HttpContext will be different in each request.