假设我有一个小型MVC Core应用程序,我想在两个数据库引擎之间切换而不会有太多麻烦(例如我有Entity Framework Core和MongoDB)。
在我的appsettings.json中,我有以下节点:
{
"UseMongo": false,
"MongoDB": {
"ConnectionString": "mongodb://127.0.0.1",
"DatabaseName": "CoreDB",
"IsSSL": true
},
"EntityDB": {
"ConnectionString": "mongodb://127.0.0.1",
"DatabaseName": "CoreDB"
}
}
然后在我的Startup.cs中,我有以下代码:
if (Configuration.GetValue<bool>("UseMongo"))
{
MongoDbContext.ConnectionString = Configuration.GetSection("MongoDB:ConnectionString").Value;
MongoDbContext.DatabaseName = Configuration.GetSection("MongoDB:DatabaseName").Value;
//Somehow inject context into application so it is available globally
}
else
{
EfDbContext.ConnectionString = Configuration.GetSection("EntityDB:ConnectionString").Value;
EfDbContext.DatabaseName = Configuration.GetSection("EntityDB:DatabaseName").Value;
//Somehow inject context into application so it is available globally
}
然后我声明了一个接口,从中导出两个存储库类:
public interface IRepository : IDisposable
{
void GetData();
}
public class EfRepository : IRepository
{
public void GetData()
{
//DB logic
}
}
public class MongoRepository : IRepository
{
public void GetData()
{
//DB logic
}
}
到目前为止一切顺利。现在我想使用任一存储库类,具体取决于我的appsettings.json中的“UseMongo”开关。我已经看了一点依赖注入,但我还没有找到解决方案。我希望能够在我的控制器中执行此操作:
public class ValuesController : Controller
{
private IRepository _repository;
public ValuesController(IRepository repository)
{
_repository= repository;
}
}
这样的事情可行吗?
答案 0 :(得分:1)
你可以这样做
if (Configuration.GetValue<bool>("UseMongo"))
{
services.AddScoped(typeof(IRepository),typeof(MongoRepository))
}
else
{
services.AddScoped(typeof(IRepository),typeof(EfRepository))
}