question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

`IHttpContextScopedAccessor` for accessing `HttpContext` from request scoped DI components

See original GitHub issue

Is 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:closed
  • Created 5 months ago
  • Comments:15 (8 by maintainers)

github_iconTop GitHub Comments

2reactions
davidfowlcommented, May 1, 2023

AsyncLocal is a potential perf leak, even if it’s a minor, it hits your brain. Most probably it’s minor, but you do not have numbers.

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.

IHttpContextAccessor.HttpContext should be used from the right execution context, you have more chances to introduce a hidden bug.

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

IHttpContextAccessor.HttpContext is nullable, but in a case of request scoped component it’s not a clean design, as it never be null as a request DI scope always bound to a request HttpContext.

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.

People who remember IIS know about it’s complicated threading model and issues of maintenance of the correct ExecutionContext, remember tons of problems with HttpContext.Current (and yes IHttpContextAccessor is exactly the same API but for AspNetCore).

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.

1reaction
davidfowlcommented, May 12, 2023

Agree with that.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Access HttpContext in ASP.NET Core
HttpContext encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP ...
Read more >
How to get Microsoft.AspNet.Http.HttpContext instance in ...
This would require some information from the HttpContext and some information from the database, and will be a request-scoped repository for ...
Read more >
C# developers! Your scoped components are more ...
Aspnet's IHttpContextAccessor implementation uses an AsyncLocal to scope the HttpContext instance to the request.
Read more >
Accessing the HttpContext from a DbContext
The only option we have is to inject the IHttpContextAccessor class through our DbContext class' constructor, and, from it, get hold of the ......
Read more >
DI scopes in IHttpClientFactory message handlers don't ...
In this post I discuss how handler DI scopes work in IHttpClientFactory, and how they're different to the request DI scope.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found