My favorite way to handle configuration in .NET Core
I am writing this blog post because I often see a configuration support proposal that uses hardcoded strings. Here’s a way to avoid it.
My way
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.
That’s it. No hardcoded strings in the code!