Welcome to the fourteenth episode of my course “Becoming a software developer” in which we will configure our application by using the appsettings.json file.
All of the materials including videos and sample projects can be downloaded from here.
The source code repository is being hosted on GitHub.
Scope
- Settings
Abstract
Settings
Quite often, we’re in need to somehow configure our software in a way that can be both controlled and provided as an argument directly via the source code.
Such goal can be achieved easily, by mapping the appsettings.json file into the appropriate so-called options classes. Please note, that you can use IOptions
At first, let’s define the following convention – we will have classes named XyzSettings where Xyz can be anything and the Settings will be removed for the sake of clarity.
For the starters, let’s add a very simple GeneralSettings class, beware that you can have as many properties and unique settings classes as you wish.
1 2 3 4 |
public class GeneralSettings { public string Name { get; set; } } |
Within appsettings.json file, add a new section named “general” that will be mapped into the “GeneralSettings” class.
1 2 3 |
"general": { "name": "Passenger" } |
It’s time to do a little bit of the magic, create a new SettingsExtensions class containing the following code:
1 2 3 4 5 6 7 8 9 10 11 |
public static class SettingsExtensions { public static T GetSettings<T>(this IConfiguration configuration) where T : new() { var section = typeof(T).Name.Replace("Settings", string.Empty); var configurationValue = new T(); configuration.GetSection(section).Bind(configurationValue); return configurationValue; } } |
Add a new Autofac module:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class SettingsModule : Autofac.Module { private readonly IConfiguration _configuration; public SettingsModule(IConfiguration configuration) { _configuration = configuration; } protected override void Load(ContainerBuilder builder) { builder.RegisterInstance(_configuration.GetSettings<GeneralSettings>()) .SingleInstance(); } } |
And register it inside the ConfigureServices() method that can be found in the Startup class:
1 |
builder.RegisterModule(new SettingsModule(Configuration)); |
And that’d be all. From that point on, you can inject directly GeneralSettings class instance that will have properly mapped properties based on the values taken from the appsettings.json configuration file.
Next
In the next episode, we will dive into the authentication using JWT, as well as storing encrypted user passwords in our application.
Pingback: Dew Drop - April 27, 2017 (#2467) - Morning Dew