using System; using APT.Infrastructure.Api; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace APT.Infrastructure.EF.Extensions { public static class SqlServerTenantExtension { public static IServiceCollection AddSqlServerPerConnection(this IServiceCollection services, string key = "default", string connectionPrefix = "tenanted", Action optionAction = null, Action dbContextSetup = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerConnection(DbIntegrationType.SqlServer, key, connectionPrefix, optionAction, dbContextSetup ?? SetUpSqlServer); } public static IServiceCollection AddSqlServerPerConnection(this IServiceCollection services, Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerConnection(CombineSettings(setupAction)); } public static IServiceCollection AddSqlServerPerTable(this IServiceCollection services, string key = "default", string connectionName = "tenanted", Action optionAction = null, Action dbContextSetup = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerTable(DbIntegrationType.SqlServer, key, connectionName, optionAction, dbContextSetup ?? SetUpSqlServer); } public static IServiceCollection AddSqlServerPerTable(this IServiceCollection services, Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerTable(CombineSettings(setupAction)); } public static IServiceCollection AddSqlServerPerSchema(this IServiceCollection services, string key = "default", string connectionName = "tenanted", Action optionAction = null, Action dbContextSetup = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerSchema(DbIntegrationType.SqlServer, key, connectionName, optionAction, dbContextSetup ?? SetUpSqlServer); } public static IServiceCollection AddSqlServerPerSchema(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 = SetUpSqlServer; setupAction?.Invoke(settings); }; } internal static void SetUpSqlServer(IServiceProvider serviceProvider, string connectionString, DbContextOptionsBuilder optionsBuilder) where TDbContext : DbContext, ITenantDbContext { var settings = serviceProvider.GetService>(); var tenant = serviceProvider.GetService(); optionsBuilder.UseSqlServer(connectionString, builder => { builder.TenantBuilderSetup(serviceProvider, settings, tenant); }); } } }