1

I am working on an ASP .NET Core application. i have to change database connection on runtime. Here i am using appsettings.json file.

Please, I have tries a lot but I nothing seems to be working so I need your help.

For example:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");
            var configuration = builder.Build();

            optionsBuilder.UseMySql(configuration
                ["ConnectionStrings:Defaultconnection"]);

        }

Thanks in advance.

3
  • 1
    how many different DbContext/connection strings are you going to have? Commented Jul 1, 2019 at 13:07
  • I have More than 50 connections... Commented Jul 1, 2019 at 13:10
  • What do you mean by ` change database connection on runtime? Do you want to modify the appsettings.json` at runtime, what is the value you want to change? Commented Jul 11, 2019 at 6:08

1 Answer 1

1

I can think of a couple of ways to do this..

1) Create a DbContextFactory which will create your instances for you. Maybe apply an attribute to each context which will allow you to fetch out the relevant db connection string from your connection string collection at the point that the factory makes the instance? A bit of reflection in the DbContextFactory would do that easy enough.

2) If the collection of DbContexts is not likely to change, and/or the connection strings either - you could register each DbContext manually using the AddDbContext<>() extension method in the ServiceCollection and then just inject the DbContext that you want into the classes you want

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.