5

Reed Copsey gave this response to the following SO Question:

Which design patterns can be applied to the configuration settings problem?

I prefer to create an interface for setting query, loading, and saving. By using dependency injection, I can inject this into each component that requires it.

Can someone give a code example of this? For instance a Settings class for an Email Client and another Settings class for a FTP Client based on this "interface" that can be DI. I understand that you can do a global singleton for all settings within the application (which I am currently doing) but this recommendations from Reed is interesting and would like to try it out.

sean e
  • 11,792
  • 3
  • 44
  • 56
cesara
  • 842
  • 1
  • 7
  • 19

1 Answers1

5

For the interface, I would do something like this:

public interface ISettingsProvider
{
    void Load();

    T Query<T>(string key);
    void Set<T>(string key, T value);

    void Save();
}

Then I would implement that interface once and dependency inject it with let's say MEF. I guess I'd implement it with LinqToXml to load/save to XML and maybe have a Dictionary to cache the settings in memory. Another way would be to binary serialize your objects and dump a snapshot somewhere (which has it's downsides, e.g. it is not human-readable).

If you only save strings and/or numbers, XML is a good choice. If you only have strings, you can even ditch the generics.

LueTm
  • 2,366
  • 21
  • 31