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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With