WPF – deal with application settings in MVVM

WPF – Application settings in MVVM

When I had to do with WPF and decided to follow the MVVM paradigm as strictly as possible, my first questions where how to treat application settings, where and when.

The best suggestion I read come from stackoverflow, so below I’ll write the code to implement what I understood from there.

For this purpose, there are no special requirements except by using any MVVM framework you like (Personally I use MVVM Foundation by Josh Smith) and an IOC container:

In my applications I always use TinyIoC because it’s considerable smart and fast.

When the application starts,  the IoC register a component that acts like a bridge between the viewmodel and the settings class by copying, loading and saving the properties.

So for this example let’s create a simple settings class that has two properties named Host and Port.

AppSettings.cs

The class above will not be directly referenced by view, viewmodel or business service.

Since we need a single instance of settings par application, the singleton pattern is our natural choice.

AppSettingsLocator.cs

Now create an interface that instead will be used to reference the app settings class and contains the abstraction of all the settings properties plus the methods Load() and Save().

IConfigProvider.cs

After creating the interface we create its implementation:

SettingsConfigProvider.cs

The class above does all the stuff we need to deal with our application settings !

Now it’s time to register the interface using the IoC at the startup of our application;

we do this by creating an event that is called when the application starts.

App.xaml

 

App.xaml.cs

Now the interface is registered, we can finally resolve it from the ViewModel:

ViewModel.cs

Final considerations

Despite the large use of code neeeded for doing this job, the strong point of adopting this pattern is the decoupling of the “business part” and the viewmodel; just think you can replace – in any moment with a minimal change of code – the SettingsConfigProvider class with another one that write and load data from a Database!