public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var provider = scope.ServiceProvider; var loggerFactory = provider.GetRequiredService <ILoggerFactory>(); var phoneBookContext = provider.GetRequiredService <PhoneBookContext>(); try { phoneBookContext.Database.Migrate(); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred while migrating the DB"); } try { PhoneBookContextSeed.SeedPhoneBooksAsync(phoneBookContext, loggerFactory).Wait(); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB's phonebook table."); } } host.Run(); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { // Create a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context (PhoneBookContext) using an in-memory // database for testing. services.AddDbContext <PhoneBookContext>(options => { options.UseInMemoryDatabase("InMemoryDb"); options.UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (PhoneBookContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <PhoneBookContext>(); var loggerFactory = scopedServices.GetRequiredService <ILoggerFactory>(); var logger = scopedServices .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >(); // Ensure the database is created. db.Database.EnsureCreated(); try { // Seed the database with test data. PhoneBookContextSeed.SeedPhoneBooksAsync(db, loggerFactory).Wait(); } catch (Exception ex) { logger.LogError(ex, $"An error occurred seeding the " + "database with test messages. Error: {ex.Message}"); } } }); }