简体   繁体   中英

Generating Roles in Startup.cs doesn't work anymore in .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();

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM