EntityFrameworkCore-启用DbContextPool时如何注入IPrincipal [英] EntityFrameworkCore - How to inject IPrincipal when DbContextPool is enabled
问题描述
我有一个aspnet核心MVC应用程序,我需要注入当前请求的 IPrincipal
,以便我知道谁是当前登录的用户.我紧随了这篇文章.
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.
现在,我需要在 Dbcontext
中使用 IPrincipal
来自动填充审核字段(CreatedBy,UpdatedBy等).天真了,我可以在我的 DbContext
构造函数中注入 IPrincipal
:
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)
但是我正在使用 DBContextPool
,它在WebAPI请求中重用 DbContext
实例.
But I am using the DBContextPool
, which reuses DbContext
instances across WebAPI requests.
在这种情况下,注入 IPrincipal
的正确方法是什么?
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
.
对于ASP网络核心应用程序,我需要一个 HttpContextClaimsPrincipalAccesor
,其中 ClaimsPrincipal
来自 HttpContext.User
For asp net core applications I need an HttpContextClaimsPrincipalAccesor
, where ClaimsPrincipal
comes from the HttpContext.User
推荐答案
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>();
// ...
}
}
这篇关于EntityFrameworkCore-启用DbContextPool时如何注入IPrincipal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!