public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var catalogContext = services.GetRequiredService <ShopDbContext>(); await ShopDbContextSeed.SeedAsync(catalogContext); } catch (Exception ex) { } } host.Run(); }
public async static Task Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var shopDbContext = services.GetRequiredService <ShopDbContext>(); await ShopDbContextSeed.SeedAsync(shopDbContext); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { var provider = services .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); services.AddDbContext <ShopDbContext>(options => { options.UseInMemoryDatabase("ShopDb"); options.UseInternalServiceProvider(provider); }).AddUnitOfWork <ShopDbContext>(); var sp = services.BuildServiceProvider(); using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <ShopDbContext>(); db.Database.EnsureCreated(); var loggerFactory = scopedServices.GetRequiredService <ILoggerFactory>(); var logger = scopedServices .GetRequiredService <ILogger <ShopWebApplicationFactory <TStartup> > >(); try { ShopDbContextSeed.SeedAsync(db).Wait(); } catch (Exception ex) { logger.LogError(ex, $"An error occurred seeding the " + "database with test messages. Error: {ex.Message}"); } } }); }