c# Initialize Appsettings from database

2019-03-02 11:02发布

问题:

We have an already existing console application which currently uses File based AppSettings.

So my app.config points to my actual appsettings file :

<appSettings configSource="Configs\StaticAppSettings.config"/>

And in the entire code we are accessing the configuration as such :

var value = ConfigurationManager.AppSettings["SomeKeyName"];

Going forward we want the appSettings to be in the Database.So if we want to keep the same codebase and just modify how we initialize the appsettings, is that going to be the right approach ?

We are planning to do something like this as initialization of appSettings :

ConfigurationManager.AppSettings["SomeKeyName"] = "SomeValue";
ConfigurationManager.AppSettings["SomeKeyName2"] = "SomeValue2";

Basically just create keys with the same key name as files have currently, but the Key and value come from DB instead of files.

This way our codebase still remains the same and all the appSettings are now initialized from DB instead of files.

Is this a correct approach or does it present some caveats / issues, or is there another better approach to read from DB without changing code everywhere ?

回答1:

Since I did not recieve any answers, I ended up doing a POC to prove my point, below is the piece of code which goes through the appsettings and updates settings from DB:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

IDictionary<string, string> staticAppSettings = ConfigService.GetStaticAppSettings(); // DB Call to get all settings from DB

foreach (var setting in staticAppSettings)
{
  if (ConfigurationManager.AppSettings[setting.Key] == null)
    config.AppSettings.Settings.Add(setting.Key, setting.Value);
  else
    ConfigurationManager.AppSettings[setting.Key] = setting.Value; // Update existing
}

config.Save();
ConfigurationManager.RefreshSection("appSettings");