public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); var usermanager = services.GetRequiredService <UserManager <ApplicationUser> >(); //create the initial roles and add them to the database RoleRepo roleRepo = new RoleRepo(context); roleRepo.CreateInitialRoles(); Seeder seeder = new Seeder(usermanager, context, services); seeder.SeedDataAsync().Wait(); } catch (Exception e) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(e, "An error occurred while seeding the database."); } } host.Run(); }
public static void Main(string[] args) { var host = BuildWebHost(args); // Revised to enable seeding. // Seed the data when the application starts. using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); var userManager = services.GetRequiredService <UserManager <Models.ApplicationUser> >(); IServiceProvider serviceProvider = services.GetRequiredService <IServiceProvider>(); //It seems like I need to keep these two lines to ensure the creation of roles. RoleRepo roleIni = new RoleRepo(context); roleIni.CreateInitialRoles(); var RoleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); var UserManager = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >(); string[] roleNames = { "Admin", "Premium", "Regular" }; Task <IdentityResult> roleResult; foreach (var roleName in roleNames) { var roleExist = RoleManager.Roles.Where(r => r.Name == roleName).FirstOrDefault(); if (roleExist != null) { //create the roles and seed them to the database: Question 1 roleResult = RoleManager.CreateAsync(new IdentityRole(roleName)); } } Initialize initializer = new Initialize(context, userManager); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while seeding the database."); } } BuildWebHost(args).Run(); }