using System.Data.Common; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore.Diagnostics; namespace CleanArchitecture.IntegrationTests.Extensions; public static class FunctionalTestsServiceCollectionExtensions { public static IServiceCollection SetupTestDatabase(this IServiceCollection services, DbConnection connection) where TContext : DbContext { var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions)); if (descriptor != null) services.Remove(descriptor); services.AddScoped(p => DbContextOptionsFactory( p, (sp, options) => options .ConfigureWarnings(b => b.Log(CoreEventId.ManyServiceProvidersCreatedWarning)) .UseLazyLoadingProxies() .UseSqlite(connection))); return services; } private static DbContextOptions DbContextOptionsFactory( IServiceProvider applicationServiceProvider, Action optionsAction) where TContext : DbContext { var builder = new DbContextOptionsBuilder( new DbContextOptions(new Dictionary())); builder.UseApplicationServiceProvider(applicationServiceProvider); optionsAction?.Invoke(applicationServiceProvider, builder); return builder.Options; } }