Home > OS >  appsettings.json change connection string on runtime
appsettings.json change connection string on runtime

Time:01-13

Asume i have 4 servers with 4 dbs they have all the same catalog. it is possible to change {serverLocation} on runtime ?

"ConnectionStrings": {  
"Euro": "Data Source=campus-db-{serverLocation};Initial Catalog=Shool;Integrated Security=True"}

method should look something like that:

    [HttpGet]
    public async Task<IActionResult> GetStock(int id, string serverLocation)
    {

        var queryStock = _context.TblItem.FindAsync(id);

        return Ok(queryStock);
    }

The idea is that i need only 1 DBContext 1 Model because on all 4 servers the catalog are the same and database structure

CodePudding user response:

This might help you, please check.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddDbContext<ApplicationDbContext>(
        options => 
    {
        // write conditional statements here like
        if(somecondition-a)
         options.UseSqlServer("name=ConnectionStrings:Connection-A"));
        if(somecondition-b)
         options.UseSqlServer("name=ConnectionStrings:Connection-B"));
    }
}

For more infor check this docs

If that do not help, try this approach

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextFactory<ApplicationDbContext>(
        options =>
   {
    // write conditional statements here like
    if(somecondition-a)
     options.UseSqlServer("name=ConnectionStrings:Connection-A"));
    if(somecondition-b)
     options.UseSqlServer("name=ConnectionStrings:Connection-B"));
   }
}

CodePudding user response:

you can write like this but i am not sure

IConfiguration _configuration;
public StockManager(IConfiguration configuration)
{
_configuration = configuration;
}

public object FindAsync(int id,serverLocation)
{
//do stuff
_configuration.GetConnectionString($"ConnectionStrings:{serverLocation}");
}


  •  Tags:  
  • Related