public static IWebHost Initialize(this IWebHost host) { using var scope = host.Services.CreateScope(); var services = scope.ServiceProvider; try { var context = services.GetRequiredService <BlogDbContext>(); context.Database.Migrate(); var userManager = services.GetRequiredService <UserManager <User> >(); Task .Run(async() => { await BlogDbContextSeed.SeedAsync(context, userManager); }) .GetAwaiter() .GetResult(); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating or seeding the database."); } return(host); }
public async static Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using var scope = host.Services.CreateScope(); var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var context = services.GetRequiredService <BlogDbContext>(); await BlogDbContextSeed.SeedAsync(context, loggerFactory); var appContext = services.GetRequiredService <ApplicationDbContext>(); await ApplicationDbContextSeed.SeedAsync(appContext, loggerFactory); } catch (Exception e) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(e, "An error occurred seeding the DB."); } host.Run(); }