Search code examples
c#asp.netdynamicconnection-string

How to dynamically change connection string ASP.NET


I'm developing an application that relies on ASP.NET C# for the back-end. I'm trying to change the connection string on the controller depending on what's coming from the request.

Example:

POST 1: access to server 10.126.0.1 db: db_manager

POST 2: access to server 10.126.0.2 db: bd2_manager

The ip and db are supposed to be input to the request and change it accordingly.

I'm currently defining the connection string in the Startup.cs (ConfigureServices method) file like this:

 string connectionString = Configuration.GetConnectionString("connection");

            services.AddSingleton<INHibernateSessionFactory>(provider => new NHibernateSessionFactory(connectionString));
            services.AddScoped(provider => provider.GetRequiredService<INHibernateSessionFactory>().OpenSession());
            services.AddScoped<IDataContext, DataContext>();

I'd like to know how can I define and change the connectionString dynamically for the duration of the request, instead of statically in the startup.


Solution

  • You can't change the settings based on the http request in ConfigureServices. Instead you should implement an abstract factory. A full response with example you may find here: How to configure services based on request in ASP.NET Core