Last active
June 12, 2020 13:41
-
-
Save kkozmic/7580276 to your computer and use it in GitHub Desktop.
Strongly typed configuration using Castle DictionaryAdapter requires castle.core nuget package
This file contains hidden or 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
<?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> |
This file contains hidden or 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
[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; | |
} | |
} |
This file contains hidden or 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
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); | |
} | |
} |
This file contains hidden or 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
[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