using System; using APT.Infrastructure.Api; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace APT.Infrastructure.EF.Extensions { public static class MySqlTenantExtension { public static IServiceCollection AddMySqlPerConnection(this IServiceCollection services, string key = "default", string connectionPrefix = "tenanted", Action optionAction = null, Action dbContextSetup = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerConnection(DbIntegrationType.Mysql, key, connectionPrefix, optionAction, dbContextSetup ?? SetUpMySql); } public static IServiceCollection AddMySqlPerConnection(this IServiceCollection services, Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerConnection(CombineSettings(setupAction)); } public static IServiceCollection AddMySqlPerTable(this IServiceCollection services, string key = "default", string connectionName = "tenanted", Action optionAction = null, Action dbContextSetup = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerTable(DbIntegrationType.Mysql, key, connectionName, optionAction, dbContextSetup ?? SetUpMySql); } public static IServiceCollection AddMySqlPerTable(this IServiceCollection services, Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return services.AddDbPerTable(CombineSettings(setupAction)); } static Action> CombineSettings( Action> setupAction = null) where TDbContext : DbContext, ITenantDbContext { return (settings) => { settings.DbContextSetup = SetUpMySql; setupAction?.Invoke(settings); }; } internal static void SetUpMySql(IServiceProvider serviceProvider, string connectionString, DbContextOptionsBuilder optionsBuilder) where TDbContext : DbContext, ITenantDbContext { var settings = serviceProvider.GetService>(); var tenant = serviceProvider.GetService(); optionsBuilder.UseMySql(connectionString, builder => { builder.TenantBuilderSetup(serviceProvider, settings, tenant); }); } } }