Skip to content

Instantly share code, notes, and snippets.

@doeringp
Last active July 12, 2016 10:36
Show Gist options
  • Save doeringp/b86b5bda17c4cc074c4db2b041e1a944 to your computer and use it in GitHub Desktop.
Save doeringp/b86b5bda17c4cc074c4db2b041e1a944 to your computer and use it in GitHub Desktop.
Dynamic Wrapper for the values in the ConfigurationManager.AppSettings dictionary.
using System.Configuration;
using System.Dynamic;
using System.Linq;
namespace AppSettingsDemo
{
/// <summary>
/// Wrapper for the values in the ConfigurationManager.AppSettings dictionary.
/// Declare an instance of the AppSettings class with the dynamic keyword and all calls
/// to any properties will lookup for the right key in the appSettings-section in you app.config
/// </summary>
public class AppSettings : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (ConfigurationManager.AppSettings.AllKeys.Contains(binder.Name))
{
result = ConfigurationManager.AppSettings[binder.Name];
return true;
}
throw new ConfigurationErrorsException(
$"There is no key \"{binder.Name}\" in appSettings-section in your application config.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment