user1019042 user1019042 - 1 year ago 264
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)

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>()

in AccountController, I tried this:

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
while attempting to activate

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download