using System; using APT.Infrastructure.Api; using APT.Infrastructure.Core; using Castle.Core.Logging; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace APT.Infrastructure.EF.Extensions { public static class PostgreTenantExtension { public static IServiceCollection AddPostgrePerConnection(this IServiceCollection services, string key = "default", string connectionPrefix = "tenanted", Action optionAction = null, Action dbContextSetup = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerConnection(DbIntegrationType.Postgre, key, connectionPrefix, optionAction, dbContextSetup ?? SetUpPostgre); } public static IServiceCollection AddPostgrePerConnection(this IServiceCollection services, Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerConnection(CombineSettings(setupAction)); } public static IServiceCollection AddPostgrePerTable(this IServiceCollection services, string key = "default", string connectionName = "tenanted", Action optionAction = null, Action dbContextSetup = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerTable(DbIntegrationType.Postgre, key, connectionName, optionAction, dbContextSetup ?? SetUpPostgre); } public static IServiceCollection AddPostgrePerTable(this IServiceCollection services, Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerTable(CombineSettings(setupAction)); } public static IServiceCollection AddPostgrePerSchema(this IServiceCollection services, string key = "default", string connectionName = "tenanted", Action optionAction = null, Action dbContextSetup = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerSchema(DbIntegrationType.Postgre, key, connectionName, optionAction, dbContextSetup ?? SetUpPostgre); } public static IServiceCollection AddPostgrePerSchema(this IServiceCollection services, Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerSchema(CombineSettings(setupAction)); } static Action> CombineSettings( Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return (settings) => { settings.DbContextSetup = SetUpPostgre; setupAction?.Invoke(settings); }; } internal static void SetUpPostgre(IServiceProvider serviceProvider, string connectionString, DbContextOptionsBuilder optionsBuilder) where TDbContext : DbContext, ITenantDbContext { //if(string.IsNullOrEmpty(connectionString)) // connectionString= var settings = serviceProvider.GetService>(); var tenant = serviceProvider.GetService(); optionsBuilder.UseNpgsql(connectionString, builder => { builder.TenantBuilderSetup(serviceProvider, settings, tenant); }); } } }