0

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?

1 Answer 1

1

You can do like this

if (Configuration.GetValue<bool>("UseMongo")) { services.AddScoped(typeof(IRepository),typeof(MongoRepository)) } else { services.AddScoped(typeof(IRepository),typeof(EfRepository)) } 
Sign up to request clarification or add additional context in comments.

4 Comments

Just one question: Is this a good practice? Because all the examples I read where DbContext is injected use services.AddDbContext for injecting a context.
How you're creating instance of DbContext? Are you creating it inside the repository or you're injecting it using DI? If you're using DI you can add AddDbContext method.
I haven't implemented that part yet but I plan to instantiate it inside my repository class so I guess I would be fine without using AddDbContext if I understand it correctly.
If you are initializing DB context inside Repository, you can't unit test them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.