0

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
  • 1
    You shouldn't. The Data project does not have to know anything about HttpContext. Why don't you pass the Items to the CustomerRepository as a simple method parameter? Commented Sep 9, 2022 at 8:51

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

He said he cannot use constructor injection, so this answer does not help him.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.