它並沒有那麼糟糕,因爲你可以根據你的環境改變連接字符串,讓您的appsetings.json的不同版本(appsettings.dev.json,appsettings.release.json等等等等)
您在您的控制器contructors coulduse這些情境另一方面,即 構造函數1:
public FirstController(db1 context)
ctor2:
public SecondController(db2 context)
也許,ALSE,ctor3:
public ThirdController(db1 contextA, db2 contextB)
但是:
一)考慮命名約定(IDB? db1 ??)
b)爲什麼你想擁有兩個相同類型的存儲庫......哦!你想要有一個通用的存儲庫模式?那麼你的答案就在這裏:https://github.com/Arch/UnitOfWork(IM使用它,我非常hapy,結果和表現,我會貼一個例子波紋管)
使用IUnitOfWork:
在你的控制器:
public YourController(IUnitOfWork unitOfWork)
{
try
{
_unitOfWork = unitOfWork;
// seeding
var ItemRepository = _unitOfWork.GetRepository<Item>();
//ETC...
在啓動,在ConfigureServices,調用此方法:
private void AddEntityFrameworkAndDbContext(IServiceCollection services)
{
services.AddEntityFrameworkSqlServer();
var migrationsAssemblyName = typeof(YourContext).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<YourContext>(options =>
{
options.UseSqlServer(Your.ConnectionString.NoMAtterHowYouGetIt,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(migrationsAssemblyName);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
}); // Man, this is for free, I spent days getting it to work
},
ServiceLifetime.Scoped // Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
).AddUnitOfWork<YourContext>();
}
而且在配置嘗試類似:
app.EnsurePopulated(app.ApplicationServices.GetRequiredService());
我希望它可以幫助你,
胡安