首页 > 解决方案 > 如何在 Asp.Net Core 2 中正确注册自定义 IdentityServer ConfigurationDbContext?

问题描述

我正在尝试从 IdentityServer 创建自己的 ConfigurationDbContext。

public class IdSrvConfigurationDbContext : ConfigurationDbContext<ConfigurationDbContext>
{
    public IdSrvConfigurationDbContext(DbContextOptions<IdSrvConfigurationDbContext> options, ConfigurationStoreOptions storeOptions) : base(options.ChangeOptionsType<ConfigurationDbContext>(), storeOptions)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //mylogic here  
        base.OnModelCreating(modelBuilder);
    }
}

现在在 Startup.cs 我尝试了以下

    services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddConfigurationStore(options =>
            {
                // (DbContextOptionsBuilder) paramBuilder
                options.ConfigureDbContext = paramBuilder =>
                    paramBuilder.UseSqlServer(connectionString,
                        sql => sql.MigrationsAssembly(migrationAssembly));
            });

现在,当我尝试在我的项目上运行迁移时,它会经历所有启动逻辑注入并以以下错误结束:

在此处输入图像描述

标签: asp.net-coreentity-framework-coreasp.net-core-2.0identityserver4entity-framework-migrations

解决方案


您需要将IdSrvConfigurationDbContext类型设置为期望 a DbContextOptions<ConfigurationDbContext>。这是底层ConfigurationDbContext期望的类型,也是 IdentityServer 将要传递的类型。

通常,您应该始终使用DbContextOptions<T>与上下文匹配的类型。但是当从现有上下文继承时,这可能有点困难。但在这些情况下,您不必担心太多:键入的选项仅用于区分各种配置的选项。因此,只要您的应用程序中的每个上下文仍然使用单独的类型,就不会有任何问题。


推荐阅读