Created
February 4, 2014 14:56
-
-
Save dlidstrom/8805081 to your computer and use it in GitHub Desktop.
Castle Windsor typed app settings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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