30 lines
1009 B
C#
30 lines
1009 B
C#
using ApiPolo.Data;
|
|
using ApiPolo.Interfaces;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
public class TenantDbContextFactory : ITenantDbContextFactory
|
|
{
|
|
private readonly IServiceProvider _serviceProvider;
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public TenantDbContextFactory(IServiceProvider serviceProvider, IConfiguration configuration)
|
|
{
|
|
_serviceProvider = serviceProvider;
|
|
_configuration = configuration;
|
|
}
|
|
|
|
public TenantDbContext GetDbContext(string tenant)
|
|
{
|
|
var optionsBuilder = new DbContextOptionsBuilder<TenantDbContext>();
|
|
|
|
string connectionString = _configuration.GetConnectionString(tenant)
|
|
?? throw new KeyNotFoundException($"No connection string found for tenant: {tenant}");
|
|
|
|
optionsBuilder.UseSqlServer(connectionString);
|
|
|
|
return new TenantDbContext(optionsBuilder.Options, _configuration, tenant);
|
|
}
|
|
}
|