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

Seeding users and roles in dbcontext in asp.net core: Circular dependency problem

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

A circular dependency was detected for the service of type '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);
 }

有什么想法吗?我应该使用 HasData 方法创建用户吗?

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

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