Home > Blockchain >  Overview of settings option in .NET 6
Overview of settings option in .NET 6

Time:10-05

I'm currently not very satisfied with the way I configure my application on C# .NET 6.

I'm using Microsoft.Extensions.Configuration library and write every configuration in the appsettings.json file. which leads to a very large file. It is also very heavy to handle as configurations are used in a lot of assemblies. My first issue due to the amount of packages has been answered here :having a section per assemblies will probably ease the management a lot. (my assemblies generally require an Iconfiguration in their constructor)

When looking for solutions in C#, I come across an issue : finding up to date information ! most answer I find are quite old and it is difficult to know if it is still good practices today in .NET 6.

It seems appsettings.json is the most wildly spread. at least for configuration that does not completely break the code if not properly set.

I found that I can set properties in Settings.settings in visual studio. Is it common practice ? for what kind of configuration ? Any advantages of using that instead of appsettings.json ?

Is there any other recommended way in .NET 6 ? for what specific application ?

where do you put settings that are sensitive and not often changed on the scope of the application ? (example: register numbers in some hardware that the application needs and that are not likely to change after commissioning )

CodePudding user response:

Idiomatic approach to manage settings (especially with DI) is to use options pattern (which allows different scenarios including for example monitoring changes of config file):

// inject, will bind data from config providers 
builder.Services.Configure<SomeServiceSpecificSettings>(
    builder.Configuration.GetSection("PathToSomeServiceSpecificSettings"));

// use
public class SomeService
{
    private readonly SomeServiceSpecificSettings _options;

    public SomeService(IOptions<SomeServiceSpecificSettings> options)
    {
        _options = options.Value;
    }

    // ...
}

Ideally you should not care about IConfiguration inside your library - you should care only about the specific settings which should be passed to it and how it will be handled usually should be handled by library consumer.

As for sensitive settings - there are multiple approaches, in some cases environment variables are used, in some - secure key storages, integrated with the build in configuration pipeline (via configuration providers).

The documentation pretty extensively covers this:

  • Related