注入RoleManager会导致错误

时间:2016-11-02 16:20:09

标签: c# asp.net-core entity-framework-core

首先,我的问题类似于此SO link,但不是相同的

我正在浏览微软的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:无法解析类型的服务   'Microsoft.AspNetCore.Identity.RoleManager`1 [MyProj.Web.Models.MyViewModels.ApplicationRole]'   在尝试激活时   'MyProj.Web.Controllers.AccountController'。

1 个答案:

答案 0 :(得分:1)

RoleManager<IdentityRole>替换为RoleManager<IdentityRole<int>>,它应该有效。