Home > Back-end >  ASP.Net Core Appsettings Best Practices
ASP.Net Core Appsettings Best Practices

Time:11-06

I'm interested to find out if there are some "best practices" that people follow when setting up a new ASP.Net Core project, as it relates to appsettings. I am aware of how the various environment-specific files work, adding to and overwriting values from the root file. What I am looking for is how people determine which settings go where. I know some who prescribe to the "universal values in base file, anything environment-specific in environment files" way of going about it. However, there is also the idea of "all production values in base file and other environment-specific overrides in the environment files." I am sure there are other approaches as well. Is there a "recommended" approach? A standard, perhaps? Does anyone have experience in multiple approaches, who could pro/con them?

CodePudding user response:

You can have a sealed class, which you can feed to IConfiguration in startup.cs

public Startup(IConfiguration configuration)
        {
            Configuration = AppConfig.Configuration;
        }

internal static IConfigurationRoot Initialize()
        {
            lock (MutexLock)
            {
                if (_configuration != null)
                {
                    return _configuration;
                };

                var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                var basePath = Environment.CurrentDirectory;

                var builder = new ConfigurationBuilder()
                    .AddEnvironmentVariables("EnvVariable")
                    .SetBasePath(basePath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{environmentName}.json", optional: true);

                return _configuration = builder.Build();
            }
        }

The environment can be set in launchsettings.json. For multiple environment, you can create multiple profiles in launchsettings.json and have multiple appsettings.json files.

CodePudding user response:

Actually, in my experience, the best way to go is the DRY (Don't Repeat Yourself) way.

Regardless of the setting value, you follow this rule:

The value that repeats the most across environments goes into appsettings.json. After doing this, override with per-environment JSON files as needed.

This is the most maintainable way of doing it because DRY is also for configuration.

  • Related