Generating Roles in Startup.cs doesn't work anymore in .NET Core 2.0

3
//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();

This piece of code generates an Admin role, account and finally adds that account to the admin role. This used to work before I upgraded to 2.0.0

Now I get this error:

System.InvalidOperationException occurred HResult=0x80131509
Message=Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' from root provider.

How can this be done in this version? Thanks!

c#
asp.net
asp.net-core
asp.net-core-2.0
asked on Stack Overflow Aug 28, 2017 by FabiGhenof • edited Aug 28, 2017 by FabiGhenof

1 Answer

3

SOLUTION

The new 2.0 Program.cs default one liner doesn't include doing this, however, the explicit way still works:

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

        host.Run();
    }
}

Also, not checking if the Role exists before creating is not forgiven anymore :D

answered on Stack Overflow Aug 28, 2017 by FabiGhenof

User contributions licensed under CC BY-SA 3.0