我有一個使用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:在創建項目以從頭開始學習標識時,我使用了「無認證」。
我建議使用個人用戶帳戶創建另一個項目,以便您可以比較使用包含身份的模板時爲您設置的內容 –
添加了「個人用戶帳戶」的全新項目不包含任何設置的代碼角色。 –
不,但它可能有一些代碼連接你沒有正確連接的依賴關係 –