Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 287
renakre Avatar asked Sep 15 '25 05:09

renakre


1 Answers

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.

like image 55
Jan Muncinsky Avatar answered Sep 17 '25 17:09

Jan Muncinsky