protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.UseEnvironment("Testing");

            builder.ConfigureServices(async services =>
            {
                // remove the existing DbContextOptions configuration
                var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions <ShoppingHelperDbContext>));

                if (descriptor != null)
                {
                    services.Remove(descriptor);
                }

                services.AddDbContext <ShoppingHelperDbContext>(options =>
                {
                    options.UseInMemoryDatabase("ShoppingHelperDbContextInMemoryTest");
                });

                var sp = services.BuildServiceProvider();

                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var context        = scopedServices.GetRequiredService <ShoppingHelperDbContext>();
                    var logger         = scopedServices.GetRequiredService <ILogger <ShoppingHelperContextSeed> >();

                    if (context.Database.EnsureCreated())
                    {
                        await ShoppingHelperContextSeed.SeedAsync(context, logger);
                    }
                };
            });
        }
Example #2
0
        public async static Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json")
                         .Build();

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(config)
                         .WriteTo.File("Logs/log-.txt", rollingInterval: RollingInterval.Day)
                         .CreateLogger();

            try
            {
                Log.Information("Starting application");

                var host = CreateHostBuilder(args).Build();

                using (var scope = host.Services.CreateScope())
                {
                    var services = scope.ServiceProvider;

                    var dbContext = services.GetRequiredService <ShoppingHelperDbContext>();
                    var logger    = services.GetRequiredService <ILogger <ShoppingHelperContextSeed> >();

                    dbContext.Database.EnsureCreated();

                    await ShoppingHelperContextSeed.SeedAsync(dbContext, logger);
                }

                host.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application terminated unexpectedly");
            }
            finally
            {
                Log.Information("Closing application.");
                Log.CloseAndFlush();
            }
        }