7

我有一个使用Identity的ASP.NET Core应用程序。它的工作原理,但是当我试图将自定义角色添加到数据库时,我遇到了问题。ASP.NET Core Identity:角色管理器没有服务

services.AddIdentity<Entities.DB.User, IdentityRole<int>>() 
       .AddEntityFrameworkStores<MyDBContext, int>(); 

services.AddScoped<RoleManager<IdentityRole>>(); 

,并在启动Configure我注入RoleManager并将它传递给我的自定义类RolesData

public void Configure(
     IApplicationBuilder app, 
     IHostingEnvironment env, 
     ILoggerFactory loggerFactory, 
     RoleManager<IdentityRole> roleManager 
    ) 
    { 

    app.UseIdentity(); 
    RolesData.SeedRoles(roleManager).Wait(); 
    app.UseMvc(); 
在启动 ConfigureServices我增加了身份和角色管理器为这样一个范围的服务

这是RolesData等级:

public static class RolesData 
{ 

    private static readonly string[] roles = new[] { 
     "role1", 
     "role2", 
     "role3" 
    }; 

    public static async Task SeedRoles(RoleManager<IdentityRole> roleManager) 
    { 

     foreach (var role in roles) 
     { 

      if (!await roleManager.RoleExistsAsync(role)) 
      { 
       var create = await roleManager.CreateAsync(new IdentityRole(role)); 

       if (!create.Succeeded) 
       { 

        throw new Exception("Failed to create role"); 

       } 
      } 

     } 

    } 

} 

该应用程序构建没有错误,但在尝试访问它,我得到以下错误时:

Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore`1[Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole]' while attempting to activate 'Microsoft.AspNetCore.Identity.RoleManager

我在做什么错?我的直觉告诉我如何将RoleManager添加为服务存在问题。

PS:在创建项目以从头开始学习标识时,我使用了“无认证”。

+0

我建议使用个人用户帐户创建另一个项目,以便您可以比较使用包含身份的模板时为您设置的内容 –

+0

添加了“个人用户帐户”的全新项目不包含任何设置的代码角色。 –

+0

不,但它可能有一些代码连接你没有正确连接的依赖关系 –

回答

7

What am I doing wrong? My gut says there's something wrong with how I add the RoleManager as a service.

登记部实际上是很好,寿”你应该删除services.AddScoped<RoleManager<IdentityRole>>(),如角色管理器是由services.AddIdentity()已经为你添加。

你的问题很可能造成一个泛型类型不匹配:当你打电话services.AddIdentity()IdentityRole<int>,您尝试解决RoleManagerIdentityRole,这是IdentityRole<string>等效(string是在ASP.NET核心身份的默认密钥类型)。

更新您的Configure方法采取RoleManager<IdentityRole<int>>参数,它应该工作。

+0

是的!谢谢你,先生!现在它工作正常。 –

+0

这是一个很好的解决方案,非常有帮助。我还建议从DatabaseInitializer中调用SeedRoles,以便CreateUsers和角色异步启动类似于'代码'公共异步任务SeedAsync(){await CreateUsersAsync();等待RolesData.SeedRoles(_roleManager);} – RussHooker