Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Created February 4, 2014 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dlidstrom/8805081 to your computer and use it in GitHub Desktop.
Save dlidstrom/8805081 to your computer and use it in GitHub Desktop.
Castle Windsor typed app settings
[AppSettings("smtp:")]
public interface SmtpConfiguration
{
string Name { get; set; }
int Port { get; set; }
string Username { get; set; }
}
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;
}
}
public class Program
{
public static void Main()
{
try
{
Run();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private static void Run()
{
var container = new WindsorContainer();
container.Register(
Component.For<SmtpConfiguration>()
.UsingFactoryMethod(Create)
.LifestyleSingleton());
var smtp = container.Resolve<SmtpConfiguration>();
Console.WriteLine("Name: {0}", smtp.Name);
Console.WriteLine("Port: {0}", smtp.Port);
Console.WriteLine("Username: " + smtp.Username);
}
private static SmtpConfiguration Create()
{
var factory = new DictionaryAdapterFactory();
return factory.GetAdapter<SmtpConfiguration>(ConfigurationManager.AppSettings);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment