Declare variables in app.config for use inside app.config

I have an app.config file where I have the same value many times in the file and he would like to change it in one place.

Sort of:

<appSettings> <add key="dbHostAddress" value="localhost" /> </appSettings> 

and then use it for my Data Souce value in my connection string like below

 <connectionStrings><add name="ConnectionString" connectionString="Data Source=I WOULD LIKE TO ACCESS THE VALUE HERE;Initial Catalog=Database;Integrated Security=True;Connect Timeout=15" /></connectionStrings> 

Can I do it somehow?

+5
source share
1 answer

You can always do something like this in code:

 var host = System.Configuration.ConfigurationManager.AppSettings["dbHostAddress"] var connectionString = System.Configuration.ConfigurationManager. ConnectionStrings["ConnectionString"] .ConnectionString.Replace("REPLACE_VALUE",host); 

You simply store the connection string using a placeholder, and then insert it into the code and replace the placeholder value with whatever you want.

 Data Source=REPLACE_VALUE;Initial Catalog=Database; Integrated Security=True;Connect Timeout=15 

Then I would create a wrapper class around the configuration values ​​so that this happens automatically when accessing the property in the code.

+3
source

Source: https://habr.com/ru/post/1261651/


All Articles