How can I access HttpContext in my data access code in ASP.NET Core?

Viewed 51

Based on my previous two questions Why thread Id changes in ASP.NET Core? and How can I access the selected locale in non-UI code in ASP.NET Core?, we decided that we want to use HttpContext in our data access code.

Our data access project is a different project. Thus we added this to DataAccess.csproj:

    <ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
    </ItemGroup>

Then in our Startup.cs we registered IHttpContextAccessor:

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Now in my CustomerRepository.cs for example, I want to get an instance of the HttpContext class, so that I can access its Items property.

I don't want constructor injection because that makes a lot of problem for our architecture and causes a huge change that we can't do now. I also don't want to pass it down as a parameter.

How can I get it?

1 Answers

I think if you're needing to access HTTP concerns in the inner layers, you should abstract it, you cant't access it in the data access layer directly.

services.AddHttpContextAccessor();
services.AddScoped<IYourHttpUserAccessor, YourHttpUserAccessor>();

then implement YourHttpUserAccessor with this code:

Public class YourHttpAccessor : IYourHttpAccessor {
    IHttpContextAccessor _httpAccessor;

    public YourHttpAccessor(IHttpContextAccessor httpAccessor) {
        _httpAccessor = httpAccessor;
    }

    public IDictionary HttpContextItems => _httpAccessor.HttpContext?.Items;
}
Related