Search code examples
.net-corerole-manager

Can't Create New Role In dotnet Core 2.1


I've been reading the dotnet core Authentication Documentation and trying to do some examples. I am able to create new users, but I ran into an issue with creating new roles. When I called the RoleManager.CreateAsync, it does not create the new role.

ApplicationContext Class:

  public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<string>, string>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }
     }

startup.cs:

   services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration["AppSetting:DefaultConnection"]));

    services.AddIdentity<ApplicationUser, IdentityRole<string>>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

My repository:

 private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signManager;
        private readonly ApplicationDbContext _context;
        private readonly RoleManager<IdentityRole<string>> _roleManager;
        public AccountRespository(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signManager, ApplicationDbContext context, RoleManager<IdentityRole<string>> roleManager)
        {
            _signManager = signManager;
            _userManager = userManager;
            _context = context;
            _roleManager = roleManager;
        }

my create Role method in the repost

public async Task CreateRoles(string roleName)
        {
            await _roleManager.CreateAsync(new IdentityRole() { Name = "Admin" });
        }

Solution

  • When I called the CreateRole method, the context had been disposed. I added the create method to the interface and call it from the controller. It's working as expected now.