0

I'm trying to work with several databases in which have the same schema structure with my .NET Core 2.2 Web application (with Dependency Injection approach + Entity Framework). I want to allow user can choose (or change) the database at runtime. so I have 2 questions.

1. Is it possible to change DbContext during the runtime?

2. Is it possible to configure(Dependency Injection) DbContext after launching the application?

If so, How?

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            ...

            services.AddDbContext<MyDbContext>(option => option.UseMySql(Configuration.GetConnectionString("DevConnection")));
            // Can I declare this after launching the app? or Can it be changed at Runtime?

            ...
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Jin Lim
  • 1,759
  • 20
  • 24
  • 1
    Instead of the context itself, inject a factory which accepts a simple key (think region/company/id). Controllers can operate directly against this in a using statement, or you can put it behind a “store” to house business logic along side it and handle the DbContext creation and disposal for you. – cwharris Jul 09 '19 at 23:37
  • Alternatively, key the DbContext injection off of a url parameter or value from the user auth token, etc. IMO this is a far more DRY approach. – cwharris Jul 09 '19 at 23:38
  • Hi, Thanks cwharris, DRY means simpler? but in that approach, how would you change dbContext during runtime? – Jin Lim Jul 10 '19 at 08:39
  • It depends on the lifetime of the dependency injected. For instance, in ASP.NET MVC, you can declare a dependency with a Request lifetime. This means that dependency will be instantiated after the request is received, before your controller is created, and destroyed after the response has been sent (or something along those lines). You can take advantage of this in your factory method by looking at a URL param or a value in the auth token to determine which DbContext you should create and inject, specific to only that request.. – cwharris Jul 15 '19 at 01:11
  • 1
    DRY is a software principle and means “Don’t repeat yourself”. You can read more about it here https://en.m.wikipedia.org/wiki/Don%27t_repeat_yourself – RooKie- Jul 15 '19 at 01:14

1 Answers1

0

I figured out. and also shared in other thread. Please check, If someone interested

https://stackoverflow.com/a/57064965/4735043

Jin Lim
  • 1,759
  • 20
  • 24