Skip to content

Instantly share code, notes, and snippets.

@kkozmic
Last active June 12, 2020 13:41
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kkozmic/7580276 to your computer and use it in GitHub Desktop.
Save kkozmic/7580276 to your computer and use it in GitHub Desktop.
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