From 271df127a6eb80923e49b53d5dd24d04bc1bf109 Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Thu, 30 May 2024 20:20:20 +0300 Subject: [PATCH] feat: add DbContext for UberDbContext --- SqlData/Persistence/DependencyInjection.cs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) 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());