CodexBloom - Programming Q&A Platform

Implementing a dynamic configuration system in a C# client application

👀 Views: 132 đŸ’Ŧ Answers: 1 📅 Created: 2025-10-17
configuration csharp dotnet C#

I'm maintaining legacy code that I'm building a feature where Currently developing a C# client application intended for a client's internal use... The application needs to pull configurations dynamically based on the user's environment (staging vs production). After doing some research, I decided to utilize the Microsoft.Extensions.Configuration library to handle this, but I'm facing challenges in properly setting it up for different environments. First, I created a `appsettings.json` file for the staging environment: ```json { "AppSettings": { "ApiUrl": "https://staging.api.example.com", "LoggingLevel": "Debug" } } ``` Then, I added an `appsettings.Production.json` for production configurations: ```json { "AppSettings": { "ApiUrl": "https://api.example.com", "LoggingLevel": "Error" } } ``` In my `Program.cs`, I set up the configuration like this: ```csharp public class Program { public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true) .Build(); var apiUrl = configuration["AppSettings:ApiUrl"]; Console.WriteLine($"API URL: {apiUrl}"); } } ``` While this setup works for reading the configuration, I noticed that when running in the staging environment, the values from `appsettings.json` seem to take precedence over those in `appsettings.Staging.json` when I specify it. My intent is for `appsettings.Staging.json` to override the main file when present. Additionally, I want to ensure that this works seamlessly during deployment. Upon running the application, I printed out the final configurations: ```csharp var section = configuration.GetSection("AppSettings"); Console.WriteLine($"Logging Level: {section["LoggingLevel"]}"); ``` The output is still showing the default values from `appsettings.json` instead of the staging ones. I've tried adjusting the order of the `.AddJsonFile` calls and even explicitly specifying the environment variable, but it doesn't seem to affect the outcome. What could I be missing in this configuration setup? Are there specific best practices I should follow to ensure dynamic configurations work reliably? Any insights would be greatly appreciated! My development environment is Windows 10. What's the correct way to implement this? I'd love to hear your thoughts on this.