Tim
Tim

Reputation: 15247

appsettings.json and Class libraries that use ConfigurationManager.AppSettings

I'm working on migrating an existing ASP.NET MVC app to ASP.NET Core. The solution has several class libraries (providing data access, services, etc). Many of those class libraries make use of the static ConfigurationManager.AppSettings["..."] way of getting the config from the web.config file.

With the ASP.NET Core app, though, there is no web.config file and it appears ConfigurationManager can't read appsettings.json.

I really like the new configuration system in ASP.NET Core, and am making use of it within the web app.

But is there a "simple" way to migrate these class libraries without having to rewrite them to use the new configuration system? Any basic replacement for the static ConfigurationManager.AppSettings["..."] calls that'll read appsettings.json? (note: we'll eventually rewrite them, but we'd rather do this one piece at a time)

Upvotes: 2

Views: 3169

Answers (2)

to StackOverflow
to StackOverflow

Reputation: 124804

If you're using .NET Standard 2.0 you can add a reference to the System.Configuration.ConfigurationManager NuGet package to get access to appSettings.

You can add an app.Config file (not web.Config) to your ASP.NET Core project to store the appSettings. This will be copied to the output folder and renamed as AppName.dll.config during the project build.

Upvotes: 2

juunas
juunas

Reputation: 58893

Disclaimer: I didn't try this with a class library, but this worked in LinqPad:

void Main()
{
    var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
        .AddInMemoryCollection(new Dictionary<string, string>
        {
            ["test"] = "test",
            ["test2:test"] = "test2"
        })
        .Build();

    foreach (var pair in config.AsEnumerable())
    {
        // Skips the (test2 = null) pair
        if (pair.Value != null)
        {
            ConfigurationManager.AppSettings.Set(pair.Key, pair.Value);
        }
    }

    ConfigurationManager.AppSettings["test"].Dump();
    ConfigurationManager.AppSettings["test2:test"].Dump();
}

You could put something like this in your initialization code. It sets all of the values available to the System.Configuration app setting collection.

Upvotes: 0

Related Questions