using BuildingBlocks.PersistMessageProcessor.Data; using BuildingBlocks.Web; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace BuildingBlocks.PersistMessageProcessor; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; public static class Extensions { public static IServiceCollection AddPersistMessageProcessor(this IServiceCollection services, IWebHostEnvironment env) { AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); services.AddValidateOptions(); services.AddDbContext((sp, options) => { var persistMessageOptions = sp.GetRequiredService(); options.UseNpgsql(persistMessageOptions.ConnectionString, dbOptions => { dbOptions.MigrationsAssembly(typeof(PersistMessageDbContext).Assembly.GetName().Name); }) // https://github.com/efcore/EFCore.NamingConventions .UseSnakeCaseNamingConvention(); }); services.AddScoped(provider => provider.GetService()); services.AddScoped(); if (env.EnvironmentName != "test") { services.AddHostedService(); } return services; } public static IApplicationBuilder UseMigrationPersistMessage(this IApplicationBuilder app, IWebHostEnvironment env) where TContext : DbContext, IPersistMessageDbContext { using var scope = app.ApplicationServices.CreateScope(); var persistMessageContext = scope.ServiceProvider.GetRequiredService(); persistMessageContext.Database.Migrate(); var context = scope.ServiceProvider.GetRequiredService(); context.Database.Migrate(); return app; } }