我有一个使用Identity的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();
这是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");
}
}
}
}
}
应用程序无错误构建,但在尝试访问时出现以下错误:
在激活“Microsoft.AspNetCore.Identity.RoleManager”时,无法解析类型为“Microsoft.AspNetCore.Identity.IRoleStore`1[Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole]”的服务。
我做错了什么?我的直觉告诉我在添加RoleManager作为服务时有问题。
附注:我在创建项目时使用了“No authentication”来从头开始学习Identity。
RoleManager
,因为这将阻止底层的DbContext
被正确处理。相反,考虑使用IServiceScopeFactory.CreateScope()
创建一个服务范围,在您的SeedRoles
方法返回时将被处理(您可以参考https://github.com/openiddict/openiddict-samples/blob/master/samples/ClientCredentialsFlow/AuthorizationServer/Startup.cs#L98-L115进行查看示例)。 - Kévin Chalet