独自の工場を作成するだけです。
public interface ITentantDbContextFactory<T>
{
T Create(string tenantId);
}
public class AppTenantDbContextFactory : ITenantDbContextFactory<AppDbContext>
{
public AppDbContext Create(string tenantId)
{
// do some validations on tenantId to prevent users from
// injecting arbitrary strings into the connection string
var builder = new DbContextOptionsBuilder<AppDbContext>();
// you can also load it from an injected option class
builder.UseSqlServer($"Server=MYSERVERHERE;Database={tenantId};Trusted_Connection=True;");
return new AppDbContext(builder.Options);
}
}
次に、必要な場所に工場を注入します。欠点は、DbContextのライブ時間を管理して処分する必要があることです。
また、あなたの工場にIDisposable
インタフェースを実装し、参照のリストを保持し、Dispose()
メソッドが呼び出されたときに、あなたの工場が一時的なものとして登録またはスコープされている場合、リクエストの終了時に行われますどの(これらを処分することができます。
を
Dictionary<string, AppDbContext>
に複数のDbContextにアクセスしてtenantId
(またはプロジェクトで呼び出されたもの)をキーとして使用する必要がある場合は、factory.Create("tenantA")
を呼び出すときに同じインスタンスを取得する必要がある場合は、Unit Unit of Workパターンが役立ちます。次にSaveChanges
メソッドを追加します。SaveChanges
のインスタンス化されたものがすべてAppDbContext
インスタンス