Injecting RoleManager results in an error

Firstly, my problem is similar to this SOA link , but not the same

I am looking at a sample of Identity from Microsoft. I started it only with user authentication, and it worked. I deleted the database because I want to use the database first. Now I'm trying to enable Roles.

My setup is similar to this for the user (works without a role) and the role (does not work):

My DB objects are configured as such:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<ApplicationUser>(e => { e.ToTable("User").HasKey(x => x.Id); e.Property(x => x.Id).HasColumnName("UserId"); }); builder.Entity<IdentityRole<int>>(e => { e.ToTable("Role").HasKey(x => x.Id); e.Property(x => x.Id).HasColumnName("RoleId"); }); 

and my context, user setup (I want to continue using the original IdentityRole)

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int> { } public class ApplicationUser : IdentityUser<int> { } 

in ConfigureServices:

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

in AccountController, I tried this:

 [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _roleManager = roleManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } 

The application still loads in the browser, and it remembers that I logged in earlier, but when I try to log out, for example, I get this error:

InvalidOperationException: cannot enable service for type 'Microsoft.AspNetCore.Identity.RoleManager`1 [MyProj.Web.Models.MyViewModels.ApplicationRole] when trying to activate' MyProj.Web.Controllers.AccountController '.

+1
source share
1 answer

Replace RoleManager<IdentityRole> with RoleManager<IdentityRole<int>> and it should work.

+1
source

Source: https://habr.com/ru/post/1237562/


All Articles