aspnet/DependencyInjection

AddScope seems not to work properly

Mys73rion opened this issue · 2 comments

We have a problem when register the IHttpContextAccessor via add scope during the startup project. When then the IHttpContextAccessor is injected into a controller the HttpContext is always null. But when register the IHttpContextAccessor as AddSingleton the system works.
I think when multiple client accessing the same web interface it could happen that the HttpContext is set to the wrong request because it is registered as singleton and lead to threading issues.
I also think that it should work when register the IHttpContextAccessor in the scope and not losing the httpcontext.
Now the question is this a bug or expected behavior. Or do I understand the scoping concept wrong.

For details see the attached sample project and TODO comments to find the problematic code parts.
Thanks for the help.
DemoScope.zip

IHttpContextAccessor is supposed to be registered as a singleton, not a scoped service. The HttpContext property uses an AsyncLocal to track the "current" HttpContext.

Sorry I didn't saw the AsyncLocal attribute when decompiled the code. My mistake. Ok then singleton should not be a problem. I will bind it as singleton. When this can have no side effects please close the issue.