Search code examples
c#asp.net-coreconfigappsettings

C# ASP.NET Core : support both appsettings.json and app.config


I have a shared the library that needs some input from the config file, let's say a database helper class with IConfiguration injected in the constructor.

I have an ASP.NET Core app that uses appsettings.json with database connection string. And there is also a .NET Core console app that uses app.config to provide a database connection string. Both of them use the helper class.

However IConfigration only supports appsettings.json format eg. configuration.GetConnectionString. Is there a way to be able to read from both app.config and appsettings.json in uniform code?


Solution

  • "configuration.GetConnectionString" actually support app.config. But it depends on how you write the config file.
    package
    Microsoft.Extensions.Configuration
    Microsoft.Extensions.Configuration.XML
    app.config

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <ConnectionStrings>
            <DefaultConnection>Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;</DefaultConnection>
        </ConnectionStrings>
    </configuration>
    
        public class DbHelper
        {
            private readonly IConfiguration configuration;
    
            public DbHelper(IConfiguration configuration)
            {
                this.configuration = configuration;
            }
            public string GetConString()
            {
                return configuration.GetConnectionString("DefaultConnection");
            }
        }
    

    Console App (app.config in debug folder)

    var builder = new ConfigurationBuilder()
        .AddXmlFile("app.config", optional: true, reloadOnChange: true);
    IConfiguration configuration = builder.Build();
    var helper = new DbHelper(configuration);
    var conString = helper.GetConString();
    

    Test result
    enter image description here