Keywords: .NET Core | Console Application | Environment Configuration
Abstract: This article provides a comprehensive guide on dynamically loading configuration files (such as appsettings.dev.json and appsettings.test.json) based on environment variables in .NET Core console applications. Analyzing the best practice solution and supplementary approaches, it systematically covers the complete workflow from project configuration and code implementation to environment variable setup, with compatibility considerations for .NET Core 1.0.0 through 3.1+, offering reusable solutions for developers.
Fundamentals of Environment-Aware Configuration
In .NET Core application development, loading appropriate configuration files based on different runtime environments (e.g., development, testing, production) is a common requirement. While ASP.NET Core provides built-in support through dependency injection and IHostingEnvironment, console applications require manual configuration for environment awareness. The core mechanism relies on the Microsoft.Extensions.Configuration namespace, determining the current environment through environment variables and then loading corresponding JSON configuration files.
Project Configuration and File Management
First, ensure configuration files are correctly copied to the output directory. Configure build options in project.json (.NET Core 1.x) or the project file:
{
"buildOptions": {
"copyToOutput": {
"include": ["appsettings*.json"]
}
}
}
This configuration ensures all files matching the appsettings*.json pattern are copied to the output directory during build, guaranteeing runtime accessibility.
Core Code Implementation
At the program entry point, determine the current environment through environment variables and build the configuration:
using Microsoft.Extensions.Configuration;
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
var configuration = builder.Build();
// Using configuration values
var connectionString = configuration.GetConnectionString("SQLConn");
Console.WriteLine($"Connection String: {connectionString}");
}
}
}
Code analysis: The AddJsonFile method loads both the base configuration file and environment-specific files, with optional:true preventing errors if files are missing, and reloadOnChange:true enabling hot reloading. AddEnvironmentVariables allows overriding configuration values through environment variables.
Environment Variable Setup
Before running the application, set environment variables to specify the current environment:
- Windows Command Prompt:
set ASPNETCORE_ENVIRONMENT=Development - PowerShell:
$env:ASPNETCORE_ENVIRONMENT="Development" - Linux/macOS:
export ASPNETCORE_ENVIRONMENT=Development
For .NET Core 3.1+, Microsoft recommends using the DOTNET_ENVIRONMENT environment variable, though ASPNETCORE_ENVIRONMENT remains compatible.
Using Generic Host (.NET Core 2.1+)
For console applications using Microsoft.Extensions.Hosting, configuration can be simplified via HostBuilder:
using Microsoft.Extensions.Hosting;
var hostBuilder = new HostBuilder()
.ConfigureHostConfiguration(config =>
{
config.AddEnvironmentVariables(prefix: "MYAPP_");
})
.ConfigureAppConfiguration((context, config) =>
{
config.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true);
})
.ConfigureServices((context, services) =>
{
// Configure dependency injection
});
var host = hostBuilder.Build();
host.Run();
This approach automatically handles environment detection through context.HostingEnvironment.EnvironmentName, supporting more complex application scenarios.
Configuration File Structure Examples
Base configuration file appsettings.json:
{
"ConnectionStrings": {
"SQLConn": "Server=localhost;Database=ProductionDB;"
},
"Logging": {
"Level": "Information"
}
}
Development environment configuration file appsettings.Development.json:
{
"ConnectionStrings": {
"SQLConn": "Server=localhost;Database=DevDB;"
},
"Logging": {
"Level": "Debug"
}
}
Environment-specific configuration files override identical settings in the base configuration, enabling environment differentiation.
Best Practices and Considerations
- Always store sensitive information (e.g., passwords, API keys) in environment variables or secret management services, not configuration files
- Use the
GetConnectionStringextension method specifically for connection strings - Consider using the
IOptions<T>pattern for strongly-typed configuration access - When running in Docker containers, passing configuration via environment variables is more secure and reliable
- During testing, ensure environment variables are correctly set to avoid using wrong configurations
Conclusion
By properly configuring project files, utilizing the ConfigurationBuilder API, and correctly setting environment variables, flexible environment-aware configuration can be achieved in .NET Core console applications. This approach not only suits simple applications but also extends to support complex enterprise scenarios, maintaining consistency with the ASP.NET Core configuration system.