Lately I’ve been playing around with API’s. Most of them need settings like AppId and AppSecret.¬†I found myself doing the same work over and over again: creating a settings class, filling the class with information and using it. So I came up with a way to leverage reflection to fill my setting classes with .config values.

Example class

A CloudMQTT setting class could have the following properties:

So let’s build something to automate the process!¬†I would like¬†it to be created and filled with the following line of C#:

1. Reading a setting from the configuration

So let’s start with the basics, reading a setting from the config. I’ve created a static class with the basic ability to read a setting by its name. To access the ConfigurationManager you’ll need to include a reference to the¬†System.Configuration.

Some settings will be required. The system should throw an error if a configuration value is missing. The exception will inform the end-user about what setting is missing in the configuration file.

Note:¬†I’m using a¬†String.IsNullOrWhiteSpace check to see if a settings has been filled. You might want to see if this fits your needs. A value with only spaces or an empty string might be something you want to support.

2. Get a value by convention

To make the system easier to work, a convention¬†for configuration-names is needed. I’m using {namespace}.{class-name}.{field-name}. My config file will look like this:

To make things more convenient, I have to add a method that resolves the configuration name and value for a given object and field:

This solution supports inner classes. Generic classes aren’t supported (as the GetType().FullName¬†returns a weird looking name).

3. Fill settings object

Any object can be filled by configuration values, so let’s create a method that takes an object and inspect its¬†properties using reflection. All instance properties that are public and settable will qualify. I’m using the standard System.ComponentModel.DataAnnotations.RequiredAttribute¬†to determine¬†if the¬†field is required. To convert the string value to the right destination type I’m using a¬†Convert.ChangeType.

Note:¬†I’m rejecting (not binding) values that are null or “”. You might need something different in your project.

4. Convenience: create a settings object

I love generics, so I added one more convenience method:

Fill ‘er up!

So let’s see how this works together in a factory pattern. Line¬†10 loads creates a filled settings object:

With a solution like this, loading settings becomes way easier. As your APIs increase, your settings in your config will remain manageable and readable.

GitHub

Want to use this solution? Great. You can find it here on GitHub: AppSettingsProvider.

Nuget

Or just Nuget it into your project:

Install-Package KeesTalksTech.Utilities.Settings»