Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free form Dynamic web.config region

With the release of .NET4 has anyone ever created a dynamic web.config element that will just let you type anything you want into the config and then you can access it all off a dynamic object?

The amount of work that goes into creating custom config sections is just over the top for seemingly no reason. This has lead me to wonder if someone has replaced the song and dance of easily needing to create 5+ classes to roll a new config section each and every time.

(Note, when I say free form I would obviously expect it to conform to a valid xml element)

like image 672
Chris Marisic Avatar asked Jun 01 '11 15:06

Chris Marisic


1 Answers

If you just want to access the appSettings section of the configuration file, you can inherit from the DynamicObject class and override the TryGetMember method:

public class DynamicSettings : DynamicObject {
    public DynamicSettings(NameValueCollection settings) {
        items = settings;
    }

    private readonly NameValueCollection items;

    public override bool TryGetMember(GetMemberBinder binder, out object result) {
        result = items.Get(binder.Name);
        return result != null;
    }
}

Then, assuming this is your app.config file:

<configuration>
  <appSettings>
    <add key="FavoriteNumber" value="3" />
  </appSettings>
</configuration>

... the 'FavoriteNumber' setting could be accessed like so:

class Program {
    static void Main(string[] args) {
        dynamic settings = new DynamicSettings(ConfigurationManager.AppSettings);
        Console.WriteLine("The value of 'FavoriteNumber' is: " + settings.FavoriteNumber);
    }
}

Note that attempting to access a key that is undefined results in a RuntimeBinderException being thrown. You could prevent this by changing the overridden TryGetMember to always return true, in which case undefined properties will simply return null.

like image 200
Justin Rusbatch Avatar answered Oct 13 '22 11:10

Justin Rusbatch