首页 > 解决方案 > 如何让 IdentityServer 与 AddDbContextPool 一起使用

问题描述

我正在尝试在使用 IdentityServer 进行身份验证的 ASP Core API 项目中利用 AddDBContextPool。问题是,要使用 PersistedGrants,您需要以这种方式设置 DBContext:

private readonly IOptions<OperationalStoreOptions> _operationalStoreOptions;

public ApplicationDbContext(
   DbContextOptions options,
   IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options)
   {
        _operationalStoreOptions = operationalStoreOptions;
   }
    
protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.ConfigurePersistedGrantContext(_operationalStoreOptions.Value);
}

AddDBContextPool 只需要一个仅将 DbContextOptions 作为参数的构造函数。所以我不能再注入 operationStoreOptions 了。

我尝试使用 Startup 类中的 AddOperationalStore(),但出现以下错误:

实体类型“DeviceFlowCodes”需要定义一个主键。如果您打算使用无密钥实体类型,请调用“HasNoKey()”。

知道我错过了什么吗?

标签: asp.net-coreidentityserver4

解决方案


我最终在我的班级中手动实现了 IPersistedGrantDbContext 接口。代码如下,以防万一这可以帮助其他人。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>, IPersistedGrantDbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options)
        {
            // No tracking needed as all transactions are disconnected
            ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }

        public DbSet<PersistedGrant> PersistedGrants { get; set; } = null!;
        public DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; } = null!;

        public Task<int> SaveChangesAsync()
        {
            return base.SaveChangesAsync();
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            OperationalStoreOptions options = new OperationalStoreOptions
            {
                DeviceFlowCodes = new TableConfiguration("DeviceCodes"),
                PersistedGrants = new TableConfiguration("PersistedGrants")
            };

            base.OnModelCreating(builder);
            builder.ConfigurePersistedGrantContext(options);
            
            // ... Rest of configuration here

        }
    }

推荐阅读