.Net Core 6 – register environment appsettings.json files

The problem

A .net core application comes with a framework that creates an appsettings.{env}.json file that can store environment specific settings.

Generally settings in appsettings.json are overridden by appsettings.{env}.json, but it does not do this out of the box.

You need to configure this as part of the setup of the application

Preconditions

So the solution code sample makes sense, lets assume we have the following in a appsettings.prod.json file.

{
  "ApiSettings": {
     "apiBaseUrl" : "https://api.website.com/api"
  }
}

Then you may have a class like

public class ApiSettings 
{
   public const string SectionName = "ApiSettings";

   public string ApiBaseUrl { get; set; }
}

The solution

I like to add a ServiceCollectionExtension class where I create extensions that can be called to implement various startup functionality

The following code block is an example of how to register your .env json files into the statup, so that environment specific attributes are used.

public static class ServiceCollectionExtensions
{
    public static void AddConfiguration(this IServiceCollection services, ConfigurationManager configuration, IWebHostEnvironment env)
    {
        configuration
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

        // register configuration options
        services.Configure<ApiSettings>(configuration.GetSection(ApiSettings.SectionName));
    }
}

In .Net 6 which is minimal and does not have a startup.cs file, the setup is initiated in the Program.cs file.

To call this Configuration extension you then call it like so.

builder.Services.AddConfiguration(builder.Configuration, builder.Environment);

The point of the final line of the registration is to register a section into the application so the IOptions works with dependency injection to gain access to your configuration.

The following code shows how this works.

public class UserService 
{

   private readonly ApiSettings _apiSettings;

   public UserService(
      IOptions<ApiSettings> apiOptions
   ) 
   {
      _apiSettings = apiOptions.value;
   }

}

This will inject the apiSettings class into your object populated with the values from the specific appsettings.json file and allows you to access _apiSettings.ApiBaseUrl anywhere within your class.

Hope this boiler plate code helps.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.