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. When I run the update-database
command, I receive the following error:
A circular dependency was detected for the service of type 'App.Models.AppDbContext'. App.Models.AppDbContext -> Microsoft.AspNetCore.Identity.UserManager -> Microsoft.AspNetCore.Identity.IUserStore
Below is the 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?
Your AppDbContext
is injected with dependency UserManager
which is injected with dependency UserStore
which is needed to be injected with dependency 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.