user1019042 user1019042 - 1 month ago 25
C# Question

Injecting RoleManager results in error

First things first, my issue is similar to this SO link, but not the same

I am going through the Identity sample from microsoft. I started it with only user authentication and it worked. I removed the DB because I want to use Database first. Now I am trying to incorporate Roles.

My setup is like this for user (works without role) and role (didn't work):

My DB entities are setup 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 keep 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 app still load on the browser and it remembers that I've logged in before but when I try to logout for example, I get this error:


InvalidOperationException: Unable to resolve service for type
'Microsoft.AspNetCore.Identity.RoleManager`1[MyProj.Web.Models.MyViewModels.ApplicationRole]'
while attempting to activate
'MyProj.Web.Controllers.AccountController'.

Answer

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

Comments