`IHttpContextScopedAccessor` for accessing `HttpContext` from request scoped DI components
See original GitHub issueIs there an existing issue for this?
- I have searched the existing issues
Is your feature request related to a problem? Please describe the problem.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped<MyComponent>();
// !!!!!!!!!!
// RUNTIME Error:
// MyComponent ->Resolve Problem-> HttpContext - not registered as Scoped service
// !!!!!!!!!!
var app = builder.Build();
app.MapGet("/weatherforecast", (MyComponent c) =>
{
return c.GetWeatherData();
});
app.Run();
public class MyComponent
{
private readonly HttpContext _httpContext;
public MyComponent(HttpContext httpContext)
{
_httpContext = httpContext;
}
public string GetWeatherData()
{
if (_httpContext.Request.Headers["x-units"] == "F")
{
return $"{20 * 9 / 5} + 32";
}
return "20 C";
}
}
Describe the solution you’d like
All scoped DI components should be able to directly resolve HttpContext or at least through IHttpContextScopedAccessor
It’s already suggested in this StackOverflow question: https://stackoverflow.com/questions/49966858/scoped-service-access-http-context-without-ihttpcontextaccessor
A middleware should setup HttpContext to some scoped DI placeholder, and then all Scoped components should be able to access HttpContext.
Additional context
The lack of suggested IHttpContextScopedAccessor forces developers who needs HttpContext in 100% Scoped component chains to use IHttpContextAccessor as the only out-of-the box workaround.
But this is wrong!
IHttpContextAccessor is a workaround for a case where you have no way to pass the HttpContext through parameters to singleton components.
Issue Analytics
- State:
- Created 5 months ago
- Comments:15 (8 by maintainers)

Top Related StackOverflow Question
It is but 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.
Yes, async locals are indeed evil but necessary in many contexts (not just in the case where you need to access it from a singleton).
This doesn’t change the nullability of the property. It has to be set by another component and if that component hasn’t run yet, it’ll be null.
Sure, but ASP.NET Core (even on IIS) works very differently to .NET Framework.
Still, I’m not convinced we should have another way to access the HttpContext from the DI container that only works in some cases.
Agree with that.