我正在尝试创建一个用于播种用户和角色数据的类。
我的种子数据类需要 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/