c# Initialize Appsettings from database

倖福魔咒の 提交于 2019-12-02 03:46:39

问题


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");


来源:https://stackoverflow.com/questions/17070088/c-sharp-initialize-appsettings-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!