Create a gist now

Instantly share code, notes, and snippets.

Strongly typed configuration using Castle DictionaryAdapter requires castle.core nuget package
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="smtp:name" value="value" />
<add key="smtp:port" value="25"/>
<add key="stuff:something" value="bla"/>
<!-- other stuff -->
</appSettings>
</configuration>
[AttributeUsage(AttributeTargets.Interface,AllowMultiple = false)]
public class AppSettingsAttribute : KeyPrefixAttribute, IDictionaryPropertyGetter, IPropertyDescriptorInitializer
{
public AppSettingsAttribute(string keyPrefix) : base(keyPrefix)
{
}
public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue,
PropertyDescriptor property, bool ifExists)
{
if (storedValue == null && IsRequired(ifExists))
{
throw new ArgumentException("No valid value for '" + key + "' found");
}
return storedValue;
}
public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors)
{
propertyDescriptor.Fetch = true;
}
private static bool IsRequired(bool ifExists)
{
return ifExists == false;
}
}
internal class Program
{
private static void Main(string[] args)
{
var factory = new DictionaryAdapterFactory();
var smtp = factory.GetAdapter<SmtpConfiguration>(ConfigurationManager.AppSettings);
Console.WriteLine(smtp.Port);
Console.ReadKey(true);
}
}
[KeyPrefix("smtp:")]
public interface SmtpConfiguration
{
string Name { get; set; }
int Port { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment