1

I'm following the tutorial on this site which talks about using the Castle DictionaryAdapterFactory and an interface to access an applications app.setting keys without using strings throughout your code.

The way it works is you define an Interface that has the key names for your app.settings

   public interface ISettings
   {
    string dog { get; }
    string cat { get; }
   }

Then use the DictionaryAdapterFactory to do the coding between the interface and your app.settings dictionary.

var factory = new DictionaryAdapterFactory();                    
var settings = factory.GetAdapter<ISettings>(ConfigurationManager.AppSettings);

Now you can access the values like this:

settings.dog
settings.cat

My question is, is it possible to have something more than a complicated than a simple getter. For example, can I tell DictionaryAdapterFactory to use a decryption method on the value of one of the keys and then return that instead of the key value?

I'm assuming that this is not possible since you can't define methods in an interface, but wanted to see if there was another way that I was missing.

leppie
  • 115,091
  • 17
  • 196
  • 297
Michael Shnitzer
  • 2,465
  • 6
  • 25
  • 34

1 Answers1

0

You can use a wrapper class to wrap your interface with a class that implements custom methods.

You add [AppSettingWrapper] over your interface:

[AppSettingWrapper]
public interface ISettings
{
string dog { get; }
string cat { get; }
}

The AppSettingWrapper class is defined in the class below and lets you do what you want in the getter and setting.

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;
    }

}

Most of this solution comes from https://gist.github.com/kkozmic/7858f4e666df223e7fc4.

Michael Shnitzer
  • 2,465
  • 6
  • 25
  • 34