我正在学习本网站上的教程,该教程介绍如何使用Castle DictionaryAdapterFactory和访问应用程序应用程序的接口。在整个代码中设置密钥而不使用字符串。
它的工作方式是定义一个具有应用程序密钥名称的接口。设置
public interface ISettings
{
string dog { get; }
string cat { get; }
}
然后使用DictionaryAdapterFactory在接口和app.settings字典之间进行编码。
var factory = new DictionaryAdapterFactory();
var settings = factory.GetAdapter<ISettings>(ConfigurationManager.AppSettings);
现在你可以访问这样的值:
settings.dog
settings.cat
我的问题是,有没有可能拥有比简单的getter更复杂的东西。例如,我可以告诉DictionaryAdapterFactory对其中一个密钥的值使用解密方法,然后返回该方法而不是密钥值吗?
我假设这是不可能的,因为你不能在接口中定义方法,但我想看看是否还有我缺少的另一种方法。
您可以使用包装器类将接口包装为实现自定义方法的类。
您在界面上添加[AppSettingWrapper]:
[AppSettingWrapper]
public interface ISettings
{
string dog { get; }
string cat { get; }
}
AppSettingWrapper类在下面的类中定义,允许您在getter和设置中执行所需操作。
public class AppSettingWrapperAttribute : DictionaryBehaviorAttribute, IDictionaryKeyBuilder, IPropertyDescriptorInitializer, IDictionaryPropertyGetter
{
public string GetKey(IDictionaryAdapter dictionaryAdapter, string key, PropertyDescriptor property)
{
return key;
}
public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue, PropertyDescriptor property, bool ifExists)
{
return storedValue;
}
public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors)
{
propertyDescriptor.Fetch = true;
}
}
大多数解决方案来自https://gist.github.com/kkozmic/7858f4e666df223e7fc4.