Reputation: 395
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!
Upvotes: 7
Views: 1747
Reputation: 24083
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();
Upvotes: 6