Change Connection String at runtime - changing each request to the API - EF Core

Asked

Viewed 14 times

0

I need to create something that changes my connection string at runtime... In my WEB API (.net 5) Every request that is made needs to be contained in the Request Header 2 parameters, Authentication and Database, which refer to an access key to access the API and the other refers to which database will be used.

My application should use a database for each client, so any request that is made will call a function that changes the connection string

My need is to change the database that my application persists the information depending on the parameter received in the request header

The system takes care of bank collections and funders, where I register my debtors and loan and contracts for it, currently all records are included in a single database, this application I am developing came from the need to have a database for each client (banks and funders)

Looking at some solutions on the internet I came across these two solutions

Attempt 1

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
var teste = connectionStringsSection.ConnectionStrings;
connectionStringsSection.ConnectionStrings["DeveloperConnection"].ConnectionString = "minha string"; // Erro estoura nessa linha
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

Error: Object Reference not set to an instance of an Object

Note: In the error line, instead of "my string" was my connection string, which I obviously removed

Attempt 2


Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection csSection = config.ConnectionStrings;
csSection.ConnectionStrings.Add(new ConnectionStringSettings("BancoProd", value, "System.Data.SqlClient"));
config.Save(ConfigurationSaveMode.Modified);

This way does not burst error, but also does not change the connection string, because the project starts running with the test database string and in this attempt 2 I tried to change to the production database and at the time of inserting something in the database, was inserted in test

My file appsetting.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ProductionConnection": "XXX",
    "DeveloperConnection": "XXX"
  }
}

In my project’s Startup it is as follows

public void ConfigureServices(IServiceCollection services)
    {
        DependencyRegister.RegisterServives(services);

        services.AddControllers();

        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DeveloperConnection")));

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "ServicoBanco.Web", Version = "v1" });
        });
    }
  • Please clarify your problem or provide additional details in order to highlight exactly what you need. The way it’s written these days it’s hard to tell exactly what you’re asking.

  • I added 2 paragraphs explaining where my need came from, hopefully this clear now

  • without going into more detail, you have to change the connectionstring at the time of opening the connection (or dbcontext constructor), and not at the time of uploading the application (startup). You will not be able to use the dependency injection, much less the appsettings.js file. ps. I have no way to test and elaborate a complete answer for you at the moment, sorry.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.