Free form Dynamic web.config region

With the release of .NET4, has anyone ever created a dynamic web.config element that simply allows you to enter anything you want into the configuration, and then you can access all of this from a dynamic object?

The amount of work that goes into creating custom configuration sections is just above the top, apparently for no reason. This made me wonder if anyone replaced the song and dances, which easily need to create 5+ classes in order to download a new configuration section each time.

(Note that when I say free form, I would obviously expect it to match the actual xml element)

+7
source share
1 answer

If you just want to access the appSettings section of the configuration file, you can inherit it 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, if this is your app.config file:

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

... the setting "FavoriteNumber" can be obtained as follows:

 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 the undefined key RuntimeBinderException . You can prevent this by changing the overridden TryGetMember to always return true , in which case the undefined properties will simply return null .

+3
source

All Articles