[英]Seeding users and roles in dbcontext in asp.net core: Circular dependency problem
I am injecting UserManager
and RoleManager
in the dbcontext file to use them for adding some users and roles when the database is first created. 我将dbcontext文件中的
UserManager
和RoleManager
注入, RoleManager
在首次创建数据库时使用它们来添加一些用户和角色。 When I run the update-database
command, I receive the following error: 当我运行
update-database
命令时,出现以下错误:
A circular dependency was detected for the service of type 'App.Models.AppDbContext'.
检测到类型为“ App.Models.AppDbContext”的服务的循环依赖关系。 App.Models.AppDbContext -> Microsoft.AspNetCore.Identity.UserManager -> Microsoft.AspNetCore.Identity.IUserStore
App.Models.AppDbContext-> Microsoft.AspNetCore.Identity.UserManager-> Microsoft.AspNetCore.Identity.IUserStore
Below is the dbcontext
: 以下是
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);
}
Any ideas? 有任何想法吗? Should I create the users with
HasData
method? 我应该使用
HasData
方法创建用户吗?
Your AppDbContext
is injected with dependency UserManager
which is injected with dependency UserStore
which is needed to be injected with dependency DbContext
. 您的
AppDbContext
注入了依赖项UserManager
,注入了依赖项UserStore
,依赖项UserStore
注入了依赖项DbContext
。 Therefore you get circular dependency problem. 因此,您会遇到循环依赖问题。
Solution is to create your users outside of DbContext
, so you don't inject those services into DbContext
. 解决方案是在
DbContext
之外创建您的用户,因此不要将这些服务注入DbContext
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.