c#从数据库初始化Appsettings [英] c# Initialize Appsettings from database

查看:121
本文介绍了c#从数据库初始化Appsettings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个已经存在的控制台应用程序,当前使用基于文件的AppSettings.

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

所以我的app.config指向我的实际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"];

展望未来,我们希望appSettings位于数据库中.因此,如果我们希望保持相同的代码库并仅修改初始化appsettings的方式,那将是正确的方法吗?

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 ?

我们正计划做类似的事情作为appSettings的初始化:

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.

这样,我们的代码库仍然保持不变,并且所有appSettings现在都从数据库而不是文件中初始化了.

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 ?

推荐答案

由于我没有收到任何答案,所以我最终做了POC来证明我的观点,下面是这段代码,这些代码通过了appsettings和update设置来自数据库:

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

这篇关于c#从数据库初始化Appsettings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆