diff --git a/SqlData/Persistence/DependencyInjection.cs b/SqlData/Persistence/DependencyInjection.cs index d200bfe..ad7c511 100644 --- a/SqlData/Persistence/DependencyInjection.cs +++ b/SqlData/Persistence/DependencyInjection.cs @@ -36,8 +36,28 @@ public static class DependencyInjection services.AddDbContext(options => UseDatabase(options).CreateDbContext(dbProvider)); + services.AddDbContext(options => + { + var providerNamespace = typeof(Mark).Namespace + "." + Enum.GetName(dbProvider); - services.AddDbContext(DbConfig); + var assembly = Assembly.GetExecutingAssembly(); + var configurationTypes = assembly.GetTypes() + .Where(t => + t is { IsNested: false, IsAbstract: false, Namespace: not null } && + t.Namespace.StartsWith(providerNamespace) && + t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))); + + var modelBuilder = new ModelBuilder(); + + foreach (var configurationType in configurationTypes) + { + var configurationInstance = Activator.CreateInstance(configurationType)!; + modelBuilder.ApplyConfiguration(configurationInstance); + } + + var dbContext = (UberDbContext)Activator.CreateInstance(typeof(UberDbContext), (DbContextOptions)UseDatabase(options).Options)!; + dbContext.ApplyConfigurations(modelBuilder); + }); services.AddScoped(provider => provider.GetRequiredService()); services.AddScoped(provider => provider.GetRequiredService());