注入RoleManager会导致错误

本文关键字:错误 RoleManager 注入 | 更新日期: 2023-09-27 18:16:03

首先,我的问题类似于这个SO链接,但不相同

我正在经历从微软的身份样本。我一开始只使用了用户身份验证,结果成功了。我删除了DB,因为我想先使用数据库。现在我正在尝试合并角色。

我的设置是这样的用户(没有角色)和角色(不工作):

我的数据库实体设置如下:

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");
        });

和我的上下文,用户设置(我想继续使用原来的IdentityRole)

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

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

在AccountController中,我尝试了这个:

[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>();
    }

应用程序仍然在浏览器上加载,它记得我以前登录过,但是当我尝试注销时,例如,我得到这个错误:

InvalidOperationException:无法解析服务类型"Microsoft.AspNetCore.Identity.RoleManager"1 (MyProj.Web.Models.MyViewModels.ApplicationRole)"在试图激活"MyProj.Web.Controllers.AccountController"。

注入RoleManager会导致错误

RoleManager<IdentityRole>替换为RoleManager<IdentityRole<int>>,应该可以工作