有没有办法覆盖ConfigurationManager.AppSettings?(Is there

2019-08-20 06:50发布

我真的希望能有办法把目前获得其设置的应用程序中使用ConfigurationManager.AppSettings [“mysettingkey”]实际拥有这些设置来自一个集中的数据库,而不是app.config文件。 我可以做一个自定义的配置部分用于处理这样的事情,但我真的不希望其他开发商在我的球队不得不改变他们的代码使用我的新DbConfiguration自定义栏目。 我只是希望他们能够调用的AppSettings他们总是有路但它可以从一个中央数据库加载。

有任何想法吗?

Answer 1:

如果你不介意周围的框架黑客和您可以合理假设应用程序上运行的.NET Framework版本(即它是一个Web应用程序或Intranet应用程序),那么你可以尝试这样的事:

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Internal;
using System.Reflection;

static class ConfigOverrideTest
{
  sealed class ConfigProxy:IInternalConfigSystem
  {
    readonly IInternalConfigSystem baseconf;

    public ConfigProxy(IInternalConfigSystem baseconf)
    {
      this.baseconf = baseconf;
    }

    object appsettings;
    public object GetSection(string configKey)
    {
      if(configKey == "appSettings" && this.appsettings != null) return this.appsettings;
      object o = baseconf.GetSection(configKey);
      if(configKey == "appSettings" && o is NameValueCollection)
      {
        // create a new collection because the underlying collection is read-only
        var cfg = new NameValueCollection((NameValueCollection)o);
        // add or replace your settings
        cfg["test"] = "Hello world";
        o = this.appsettings = cfg;
      }
      return o;
    }

    public void RefreshConfig(string sectionName)
    {
      if(sectionName == "appSettings") appsettings = null;
      baseconf.RefreshConfig(sectionName);
    }

    public bool SupportsUserConfig
    {
      get { return baseconf.SupportsUserConfig; }
    }
  }

  static void Main()
  {
    // initialize the ConfigurationManager
    object o = ConfigurationManager.AppSettings;
    // hack your proxy IInternalConfigSystem into the ConfigurationManager
    FieldInfo s_configSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.Static | BindingFlags.NonPublic);
    s_configSystem.SetValue(null, new ConfigProxy((IInternalConfigSystem)s_configSystem.GetValue(null)));
    // test it
    Console.WriteLine(ConfigurationManager.AppSettings["test"] == "Hello world" ? "Success!" : "Failure!");
  }
}


Answer 2:

无论你做什么,你将需要添加重定向的一层? ConfigurationManager.AppSettings [“钥匙”]总是会在配置文件中 你可以做一个ConfigurationFromDatabaseManager但是这会导致使用不同的调用语法:

ConfigurationFromDatabaseManager.AppSettings["key"] instead of ConfigurationSettings["key"].


Answer 3:

我不知道你可以覆盖它,但你可以尝试的AppSettings的Add方法添加您的数据库设置应用程序启动时。



Answer 4:

我会尝试写一个应用程序启动并从数据库到应用程序域加载的设置。 因此,应用程序不知道它是如何生成的配置任何东西。 使用machiene.config直接通向DLL地狱2.0。



Answer 5:

如果你可以节省您修改配置文件保存到磁盘 - 你可以加载在不同的应用领域替代配置文件:

AppDomain.CreateDomain("second", null, new AppDomainSetup
{
    ConfigurationFile = options.ConfigPath,
}).DoCallBack(...);


Answer 6:

它似乎有一种方法通过设置在machine.config中的定义的appSettings节中有的allowOverride属性来做到这一点.NET 3.5中。 这使您可以覆盖在自己的app.config文件的整个部分,并指定一个新的类型来处理它。



文章来源: Is there a way to override ConfigurationManager.AppSettings?