EntityFrameworkCore - How to inject IPrincipal when DbContextPool is enabled

只愿长相守 提交于 2021-01-28 04:41:32

问题


I have an aspnet core MVC application, and I need to inject the IPrincipal of the current request so that I know who is the current logged in user. I followed this article with no problem.

Now I need the IPrincipal in my Dbcontext to auto-populate audit fields (CreatedBy, UpdatedBy, etc). Being naive I could inject the IPrincipal in my DbContext constructor:

public MyDBContext(DbContextOptions<MyDBContext> options, IPrincipal principal)

But I am using the DBContextPool, which reuses DbContext instances across WebAPI requests.

What's the proper way to inject IPrincipal in this scenario?

------------------- Update ----------------------

I am thinking I can follow the same approach as the HttpContextAccesor, and create a IClaimsPrincipalAccessor, register it as a singleton and inject it into my Dbcontext.

For asp net core applications I need an HttpContextClaimsPrincipalAccesor, where ClaimsPrincipal comes from the HttpContext.User


回答1:


You can register the IPrincipal as a Transient service on your Startup, like:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddTransient<IPrincipal>(provider => 
                provider.GetService<IHttpContextAccessor>().HttpContext.User);
    // ...
}

Then on your DbContext constructor you can inject the IServiceProvider that will allow you to get the current IPrincipal instance, for example:

public class YourDbContext : DbContext
{
    private IServiceProvider _services;
    public YourDbContext(IServiceProvider services)
    {
        _services = services;
    }
    public void SomeMethod()
    {
        var principal = _services.GetService<IPrincipal>();
        // ...
    }
}


来源:https://stackoverflow.com/questions/46675332/entityframeworkcore-how-to-inject-iprincipal-when-dbcontextpool-is-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!