我需要访问 AppDbContext 中的 HttpContextAccessor,以便我可以提取声明。
但是,由于并发要求,我得到了一个被池化的 AppDbContext:
services.AddPooledDbContextFactory<AppDbContext>((service, options) =>
{
options.UseNpgsql(connStr).UseLoggerFactory(service.GetRequiredService<ILoggerFactory>());
});
依赖注入在这种情况下不起作用,我一直在研究 GetService 概念,但无法弄清楚。
问题是我现在如何访问 AppDbContext 内的 IHttpContextAccessor 服务,以便我可以从中提取我需要的信息。
这是我在 .Net 7 中使用 Microsoft.EntityFrameworkCore 包内的 IInfrastruction 接口所做的事情
根据 Microsoft https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastruct.iinfrastruct-1?view=efcore-7.0
此接口由类型显式实现,以隐藏不打算在应用程序代码中使用但可以在数据库提供程序等编写的扩展方法中使用的属性。
public class AppDbContext : IdentityDbContext<AppUser, AppRole, long>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
_httpContextAccessor = this.GetService<IHttpContextAccessor>();
}
public DbSet<AppUser> AppUsers { get; set; }
public DbSet<AppRole> AppRoles { get; set; }
/*
* Codes shortened for brevity
*/
}