此解决方案适用于多租户类型的场景,在这些场景中,您具有相同的架构,并且需要根据租户在不同的数据库上运行相同的查询。
您可以拥有单个 DbContext,但动态传递 ConnectionString 以连接到不同的数据库。
由于您只有一个 DbContext,因此您的所有存储库都将依赖于该 DbContext。尽管您需要根据租户将正确的连接字符串传递给 DbContext。
您可以创建并实施ITenantDbContextFactory
它将查看请求以确定要使用哪个 ConnectionString 并基于该连接创建 DbContext
setup ITenantDbContextFactory
在依赖注入中
public class TenantDbContextFactory : ITenantDbContextFactory
{
public TenantDbContext GetDbContext()
{
string country;
// Read Request to identify correct tenant
switch (country)
{
case "SG":
return new TenantDbContext("connectionstring for Sg")
break;
case "MY":
return new TenantDbContext("connectionstring for my")
break;
}
}
}
public class TenantDbContext: DbContext
{
public DbSet<Company> Companies { get; set; }
public TenantDbContext(DbContextOptions<TenantDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
public class TenantUnitOfWork: ITenantUnitOfWork
{
private readonly TenantDbContext tenantDbContext;
public TenantUnitOfWork(ITenantDbContextFactory tenantDbContextFactory)
{
this.tenantDbContext= tenantDbContextFactory.GetDbContext();
}
public TenantDbContext TenantDbContext { get { return tenantDbContext; } }
public CompanyRepository CompanyRepo { get { return new CompanyRepository(tenantDbContext); } }
public void Dispose()
{
tenantDbContext.Dispose();
}
}
public class CompanyRepository
{
protected readonly TenantDbContext tenantDbContext ;
public CompanyRepository(TenantDbContext tenantDbContext)
{
this.tenantDbContext = tenantDbContext ;
}
public async Task<List<Company>> GetCompanies()
{
List<Company> companies = new List<Company>();
companies = await tenantDbContext.Companies.Where(x => x.Company_Status == "A" && x.Status == "0").ToListAsync();
return companies;
}
}