lets say I have a small MVC Core application where I want to switch between two database engines without much hassle (as an example I have Entity Framework Core and MongoDB).
In my appsettings.json, I have the following nodes:
{
"UseMongo": false,
"MongoDB": {
"ConnectionString": "mongodb://127.0.0.1",
"DatabaseName": "CoreDB",
"IsSSL": true
},
"EntityDB": {
"ConnectionString": "mongodb://127.0.0.1",
"DatabaseName": "CoreDB"
}
}
Then in my Startup.cs, I have the following code:
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
}
I then declare an interface from which two repository classes derive:
public interface IRepository : IDisposable
{
void GetData();
}
public class EfRepository : IRepository
{
public void GetData()
{
//DB logic
}
}
public class MongoRepository : IRepository
{
public void GetData()
{
//DB logic
}
}
So far so good. Now I want to use either repository class depending on the "UseMongo" switch in my appsettings.json. I have looked a little into dependency injection but I haven't found a solution. I want to be able to do this in my Controllers:
public class ValuesController : Controller
{
private IRepository _repository;
public ValuesController(IRepository repository)
{
_repository= repository;
}
}
Is something like this doable?