Quotidien Shaarli

Tous les liens d'un jour sur une page.

October 25, 2023

Note:

This is a sample appsettings.json file:

{
"ExampleConfig": {
"ValueA": "aaa",
"ValueB": "https://example.com",
"ValueC": 1234
}
}
This is our example model which we want to load from the configuration:

public class ExampleConfig
{
public string ValueA { get; set; }
public Uri ValueB { get; set; }
public int ValueC { get; set; }
}
Here’s how I read the model from the configuration:

public class ExampleCommandHandler
{
private readonly IConfiguration _configuration;

public ExampleCommandHandler(IConfiguration configuration)
{
    _configuration = configuration;
}

public Task Handle(ExampleCommand)
{
    var exampleConfig = _configuration
        .GetSection(nameof(ExampleConfig))
        .Get<ExampleConfig>()
        ?? throw new ConfigurationException(nameof(ExampleConfig));

    // ...
}

}
There is one thing you need to watch out for. To call the Get<T> method, use Microsoft.Extensions.Configuration.Binder NuGet package.