2017-01-02 152 views
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