.Net Core 3.1 adding additional config.json file to configuration argument in Startup

Viewed 7982

I need to add another configuration file to my .Net Core Blazor project. Other sources (such as this) mention using configuration builder in .Net core 2.2, but since in 3.1 the configuration is passed as a parameter into Startup, I have no way of appending another config onto it as far as I can tell. Maybe I'm looking at it wrong, but I'm assuming that the configuration passed in as a param has important configuration properties, therefor building it my self with just the additional config file seems like it leave those config properties out.

Ex: Doesn't work but should paint a picture of what I'm trying to do.

public Startup(IConfiguration configuration)
{
      Configuration = configuration;
      var builder = new ConfigurationBuilder(configuration)
              .AddJsonFile("accountconstants.json", optional: true, reloadOnChange: true);
      });
}
2 Answers

You can do it in Program.cs i.e. earlier in the pipeline rather than in Startup.cs.

Example:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostContext, config) =>
            {
                var env = hostContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Your approach should work, but needs a little bit of tweaking.

The configuration that you create needs to be added to the DI Container. The documentation for this is here.

I've achieved it as well in Azure Functions and other projects through the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IConfiguration>(provider => new ConfigurationBuilder()
            .AddEnvironmentVariables()
            .AddJsonFile("accountconstants.json", optional: true, reloadOnChange: true)
            .Build());
}
Related