my project uses App.config to read config property. Example:
ConfigurationManager.AppSettings["MaxThreads"]
Do you know of a library which I can use to read config from json. Thanks.
Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.
In the Main method, add the following code: class Program { static void Main(string[] args) { //.... IConfiguration Config = new ConfigurationBuilder() . AddJsonFile("appSettings.
The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.
The ConfigurationManager
static class is not generally available in ASP.NET Core. Instead you should use the new ConfigurationBuilder
system and strongly typed configuration.
For example, by default, a configuration is built up in your Startup
class using something similar to the following:
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();
}
This will load configuration from the appsettings.json
file and append the keys the configuration root. If you have an appsettings file like the following:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ThreadSettings" : {
"MaxThreads" : 4
}
}
Then you can then create a strongly typed ThreadSettings
class similar to the following:
public class ThreadSettings
{
public int MaxThreads {get; set;}
}
Finally, you can bind this strongly typed settings class to your configuration by adding a Configure
method to your ConfigureServices
method.
using Microsoft.Extensions.Configuration;
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ThreadSettings>(Configuration.GetSection("ThreadSettings"));
}
You can then inject and access your settings class from anyother place by injecting it into the constructor. For example:
public class MyFatController
{
private readonly int _maxThreads;
public MyFatController(ThreadSettings settings)
{
maxThreads = settings.MaxThreads;
}
}
Finally, if you really need access to the underlying configuration you can also inject that in ConfigureServices
to make it available in your classes.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(Configuration);
}
You can read more about configuration on the docs or on various blogs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With