在Startup.cs中生成角色在.NET Core 2.0中不再起作用

时间:2017-08-28 06:41:49

标签: c# asp.net asp.net-core asp.net-core-2.0

//Creates the admin ROLE
new RoleSeed(app.ApplicationServices.GetService<RoleManager<IdentityRole>>()).Seed().GetAwaiter().GetResult();
//Creates the admin ACCOUNT
new AccountSeed(app.ApplicationServices.GetService<UserManager<ApplicationUser>>()).Seed().GetAwaiter().GetResult();
//Adding ACCOUNT to ROLE
new AccToRoleSeed(app.ApplicationServices.GetService<UserManager<ApplicationUser>>(),
    app.ApplicationServices.GetService<ApplicationDbContext>()).Seed().GetAwaiter().GetResult();

这段代码生成管理员角色,帐户,最后将该帐户添加到管理员角色。 这曾经在我升级到2.0.0之前工作

现在我收到了这个错误:

  

发生System.InvalidOperationException HResult = 0x80131509
  Message = 无法解析作用域服务   &#39; Microsoft.AspNetCore.Identity.RoleManager`1 [Microsoft.AspNetCore.Identity.IdentityRole]&#39;   来自root provider。

在这个版本中如何做到这一点?谢谢!

1 个答案:

答案 0 :(得分:3)

<强>解

新的2.0 Program.cs默认一个班轮不包括这样做,但是,显式方式仍然有效:

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
          .UseKestrel()
          .UseContentRoot(Directory.GetCurrentDirectory())
          .UseIISIntegration()
          .UseStartup<Startup>()
          .Build();

        host.Run();
    }
}

此外,在创建之前不检查角色是否存在不再被原谅:D