在asp.net core中的dbcontext中播种用户和角色:循环依赖问题

ren*_*kre 4 c# entity-framework dependency-injection asp.net-identity asp.net-core

我在 dbcontext 文件中注入UserManager和 ,RoleManager以便在首次创建数据库时使用它们添加一些用户和角色。当我运行该update-database命令时,我收到以下错误:

检测到“App.Models.AppDbContext”类型的服务存在循环依赖关系。App.Models.AppDbContext -> Microsoft.AspNetCore.Identity.UserManager -> Microsoft.AspNetCore.Identity.IUserStore

下面是dbcontext

public class AppDbContext : IdentityDbContext
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public AppDbContext(
        DbContextOptions<SynergyDbContext> options,
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager
        ) : base(options) {

        _userManager = userManager;
        _roleManager = roleManager;
    }

    modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() });

     ApplicationUser user = new ApplicationUser
     {
         //implementation details
     };

     IdentityResult result = _userManager.CreateAsync(user, "password").Result;
     if (result.Succeeded) _userManager.AddToRoleAsync(user, "Admin").Wait();

     base.OnModelCreating(modelBuilder);
 }
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?HasData我应该用方法创建用户吗?

Jan*_*sky 5

AppDbContext注入了依赖项UserManager,该依赖项注入了依赖项UserStore,而该依赖项需要注入依赖项DbContext。因此你会遇到循环依赖问题。

解决方案是在 之外创建用户DbContext,这样您就不会将这些服务注入到 中DbContext