注入RoleManager會導致錯誤

asp.net-core c# entity-framework-core

首先,我的問題類似於這個SO鏈接 ,但不一樣

我正在瀏覽微軟的Identity樣本。我只使用用戶身份驗證啟動它,它工作。我刪除了數據庫,因為我想首先使用數據庫。現在我想嘗試合併角色。

我的設置對於用戶(無角色工作)和角色(不起作用)是這樣的:

我的數據庫實體設置如下:

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:嘗試激活'MyProj.Web.Controllers.AccountController'時,無法解析類型'Microsoft.AspNetCore.Identity.RoleManager`1 [MyProj.Web.Models.MyViewModels.ApplicationRole]'的服務。

一般承認的答案

通過RoleManager<IdentityRole<int>>替換RoleManager<IdentityRole> ,它應該可以工作。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow