Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core consuming standard .NET Library using ConfigurationManager.AppSettings

I have a standard .NET 4.5.2 library that I've been using for years. It has a dependency on ConfigurationManager.AppSettings which means that I've had to ensure a certain set of settings are in the appSettings section of my app or web.config files. There is no way to pass these values in. You HAVE to put them in the appSettings section.

I'm starting a new project in .NET Core but targeting Net452 so that I can leverage a number of libraries (which so far is working fine).

I'm hitting a problem with this latest library because I can't figure out how to get the settings properly set up so that ConfigurationManager.AppSettings will find them.

Putting them in appSettings.json doesn't seem to work. Putting them in a web.config doesn't seem to work, either.

Is this even possible?

Thanks!

like image 970
retsvek Avatar asked Sep 15 '16 20:09

retsvek


People also ask

Does ConfigurationManager work in .NET Core?

ConfigurationManager was added to support ASP.NET Core's new WebApplication model, used for simplifying the ASP.NET Core startup code.

What is the use of ConfigurationManager Appsettings?

Provides configuration system support for the appSettings configuration section.

Can I add more than two Appsettings json files in dotnet core?

Of course, we can add and use multiple appsettings. json files in ASP.NET Core project. To configure and read data from your custom json files, you can refer to the following code snippet. Host.


1 Answers

Yes it is possible what you want, but you should do manually(I don't know if there is an easy way).

Assume you have some settings in appsettings.json like below:

{
    "AppSettings" : {
        "Setting1": "Setting1 Value"
     }
}

In the Startup.cs constructor set ConfigurationManager.AppSettings with value:

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

        // copy appsetting data into ConfigurationManager.AppSettings
        var appSettings = Configuration.GetSection("AppSettings").GetChildren();
        foreach (var setting in appSettings.AsEnumerable())
        {
            ConfigurationManager.AppSettings[setting.Key] = setting.Value;
        }
    }

And get value in the class library:

var conStr =  ConfigurationManager.AppSettings["Setting1"].ToString();
like image 187
adem caglin Avatar answered Nov 13 '22 09:11

adem caglin