它并没有那么糟糕,因为你可以根据你的环境改变连接字符串,让您的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());
我希望它可以帮助你,
胡安