22

I really want to be able to have a way to take an app that currently gets its settings using ConfigurationManager.AppSettings["mysettingkey"] to actually have those settings come from a centralized database instead of the app.config file. I can make a custom config section for handling this sort of thing, but I really don't want other developers on my team to have to change their code to use my new DbConfiguration custom section. I just want them to be able to call AppSettings the way they always have but have it be loaded from a central database.

Any ideas?

6 Answers 6

25

If you don't mind hacking around the framework and you can reasonably assume the .net framework version the application is running on (i.e. it's a web application or an intranet application) then you could try something like this:

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!");
  }
}
4
  • 6
    private reflection... very naughty. Mar 4, 2011 at 21:47
  • what does .net framework version have specifically to do with the above example? i.e.... i am trying out a similar example, but though SetValue seems to be setting the value, trying to retrieve the configuration setting fails in the end - so, in what cases the above code might not work? thank you Dec 18, 2014 at 12:53
  • 2
    The s_configSystem private field is an implementation detail of ConfigurationManager and it might change in a future framework release or might not exist at all (for example mono has a field named configSystem instead). Dec 18, 2014 at 15:16
  • 1
    Way too complicated and has a lot of issues, such as infinite recursion (if you use a database context in GetSection) and only works with static configuration that does not change at runtime. Apr 20, 2017 at 14:41
1

Whatever you do you will need to add one layer of redirection? ConfigurationManager.AppSettings["key"] will always look in the configuration file. You can make a ConfigurationFromDatabaseManager but this will result in using different calling syntax:

ConfigurationFromDatabaseManager.AppSettings["key"] instead of ConfigurationSettings["key"].
2
  • 4
    i think the reason for the question is the need to override the existing usage that is all over the code to remove the need for extensive code base changes. could be wrong though. Aug 12, 2009 at 12:53
  • 1
    Yet, this is the only clean solution that exists (unless you are creating an Azure web application, where you can set app settings through the Azure portal). Apr 20, 2017 at 14:40
0

I'm not sure you can override it, but you can try the Add method of AppSettings to add your DB settings when the applications starts.

0

I would try to write an application starter and load the settings from the database to the application domain. So the app doesn't know anything about how it's configuration is generated. Using machiene.config leads directly into dll-hell 2.0.

1
  • What's this applicationstarter thing you're talking about? Feb 1, 2013 at 18:31
0

If you can save you modified config file to disk - you can load alternative config file in different application domain:

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

It appears there is a way to do this in .NET 3.5 by setting the allowOverride attribute in the appSettings definition section of machine.config. This allows you to override the entire section in your own app.config file and specify a new type to handle it.

1
  • 3
    I think this missed the point of the question. My reading of the question is how to override app.config, not how to use app.config to override machine.config. Feb 1, 2013 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.