问题
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