c# - 注册多个 DbContext 时,如何解析 ConfigureServices 中正确的 DbContext 类型

标签 c# asp.net entity-framework asp.net-identity

我正在尝试创建一个用于播种用户和角色数据的类。

我的种子数据类需要 RoleManager构造函数参数

public class IdentityDataSeeder
{
   private readonly RoleManager<IdentityRole> roleManager;

   public IdentityDataSeeder(RoleManager<IdentityRole> roleManager)
   {
      this.roleManager = roleManager;
   }

   public async Task SeedData()
   {
      // Do stuff with roleManager
   }
}

我从 Main 调用它像这样

public static async Task Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var dataSeeder = scope.ServiceProvider.GetService<IdentityDataSeeder>();
        await dataSeeder.SeedData();
    }

    host.Run();
}

我像这样配置我的依赖项(请注意,我的应用程序中有两个 DbContexts;一个上下文有我的身份表,另一个上下文有我的应用程序表)。

public void ConfigureServices(IServiceCollection services)
{
   services.AddDbContext<MyIdentityDbContext>(options =>
      options.UseSqlServer(
      Configuration.GetConnectionString("DefaultAdminConnection")));
   services.AddDbContext<MyApplicationDbContext>(options =>
      options.UseSqlServer(
      Configuration.GetConnectionString("DefaultConnection")));

   services.AddScoped<IdentityDataSeeder, IdentityDataSeeder>();
   services.AddScoped<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>();
   services.AddScoped<RoleManager<IdentityRole>, RoleManager<IdentityRole>>();
}

我的两个上下文类如下所示

public class MyIdentityDbContext : IdentityDbContext
{
   // ...
}

public class MyApplicationDbContext : DbContext
{
   // ...
}

当我运行程序时,出现错误

InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.RoleStore1[Microsoft.AspNetCore.Identity.IdentityRole]'.

我认为问题是因为我有两个 DbContext在我的依赖项中注册后,服务提供商在尝试解析 RoleStore 时无法确定要使用哪一个。 (如果我错了请纠正我)。

如何告诉服务提供商注入(inject)MyIdentityDbContext依赖于 RoleStore

最佳答案

您需要将工厂委托(delegate)与ActivatorUtilities Class一起使用它使用通过提供程序解析的特定DbContext

//...

services.AddScoped<IRoleStore<IdentityRole>>( sp => {
    DbContext context = sp.GetService<MyIdentityDbContext>();

    return ActivatorUtilities.CreateInstance<RoleStore<IdentityRole>>(sp, context);
});

//...

解析角色存储时,服务提供者将使用提供的DbContext并解析要注入(inject)到实例中的剩余依赖项。

关于c# - 注册多个 DbContext 时,如何解析 ConfigureServices 中正确的 DbContext 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68230580/

相关文章:

c# - 有没有办法避免在 Xamarin 中每个方法的 setter 中调用 NotifyChanged?

c# - 如何让这段代码更干?

c# - Azure 字符串未被识别为有效的日期时间

c# - ASP 转发器从 div 溢出

asp.net-mvc - 帮助 asp.net mvc 嵌套模型绑定(bind)

c# - 我的 Windows Phone 应用程序可以自动启动吗?

.net - 如何从 web.config 引用程序集?

asp.net - WSDL.exe 工具的/serverInterface 和/server 选项有什么用

c# - Entity Framework : more than one entity have the same primary key value

c# - DbContext 对象在循环内不起作用