我有一个使用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:在创建项目以从头开始学习标识时,我使用了“无认证”。
我建议使用个人用户帐户创建另一个项目,以便您可以比较使用包含身份的模板时为您设置的内容 –
添加了“个人用户帐户”的全新项目不包含任何设置的代码角色。 –
不,但它可能有一些代码连接你没有正确连接的依赖关系 –