You can always use multiple json configuration files in building configuration of a .net core application. You can also include XML configuration file.
I have very little to no knowledge about the the configuration structure and the values you are using. So here I will explain with a simple configuration examples and a asp.net core application.
I have two configuration files.
- appsettings.json
- apisettings.json
Both the above configuration files have multiple configuration sections in them.
//appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"DbSettings": {
"ConnectionString": "Data Source=localhost; Initial Catalog=CareCMSDatabase;User ID=sa; Password=Password1; TimeOut=30;"
},
"SmtpSettings": {
"UserName": "[email protected]",
"Host": "someserver.smtp.com",
"Port": "587",
"Password": "password"
}
}
//apisettings.json
{
"ProductApi": {
"BaseUrl": "https://www.products.com/",
"AuthEndpoint": "api/2.0/Auth/",
"ClientId": "somelcientid",
"ClientSecret": "someclientsecret"
},
"SearchApi": {
"BaseUrl": "https://www.search.com/",
"RandomEndpoint": "api/random",
"AuthToken": "sometoken"
}
}
Then I create C# classes to represent the configuration sections.
public class SmtpSettings
{
public string Host { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int Port { get; set; }
}
public class DbSettings
{
public string ConnectionString { get; set; }
}
public class ProductApiSettings
{
public string BaseUrl { get; set; }
public string AuthEndpoint { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
}
public class SearchApiSettings
{
public string BaseUrl { get; set; }
public string RandomEndpoint { get; set; }
public string AuthToken { get; set; }
}
Now I add these JSON files to the configuration builder while building Creating HostBuilder in Program.cs file.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration((builder) => {
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile("apisettings.json")
.AddEnvironmentVariables();
});
webBuilder.UseStartup<Startup>();
});
The above code will add the json configuration files to the configuration builder and build the configuration.
I can now retrieve the configuration sections and translate them to C# classes and use the configuration values. In following code I am accessing the configuration sections and their values inside ConfigureServices
method of Startup
class.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Get DbSettings section from the configuration file.
var dbSettingSection = Configuration.GetSection("DbSettings");
// Get Configuration value and convert it to C# class object.
var dbSettings = dbSettingSection.Get<DbSettings>();
// Now I can access ConnectionString value from the configuration by accessing dbSettings.ConnectionString
//Same as above, get ProductApi Section from the configuration file.
var productApiSection = Configuration.GetSection("ProductApi");
// Get the configuartion value and convert it to C# class object.
var productApiSettings = productApiSection.Get<ProductApiSettings>();
var smtpSection = Configuration.GetSection("SmtpSettings");
var smtpSettings = smtpSection.Get<SmtpSettings>();
var searchApiSection = Configuration.GetSection("SearchApi");
var searchApiSettings = searchApiSection.Get<SearchApiSettings>();
var authToken = Configuration["SearchApi:AuthToken"];
services.AddControllersWithViews();
}
You can also inject these configuration sections as dependencies in other parts of the application such as controller or service class.
For that, you need to add the configuration sections to the service collections so that they get resolved as dependencies. Change ConfigureService method as following.
public void ConfigureServices(IServiceCollection services)
{
var dbSettingSection = Configuration.GetSection("DbSettings");
// Add the section to service collection.
services.Configure<DbSettings>(dbSettingSection);
var productApiSection = Configuration.GetSection("ProductApi");
services.Configure<ProductApiSettings>(productApiSection);
var smtpSection = Configuration.GetSection("SmtpSettings");
services.Configure<SmtpSettings>(smtpSection);
var searchApiSection = Configuration.GetSection("SearchApi");
services.Configure<SearchApiSettings>(searchApiSection);
services.AddControllersWithViews();
}
Now I can have dependency on, let say ProductApi
config section, in my HomeController as following.
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
// Field for ProductApiSettings
private ProductApiSettings _productApiSettings;
public HomeController(IOptions<ProductApiSettings> productsApiSettings, Logger<HomeController> logger)
{
_logger = logger;
// Initilizing settings object from the dependency.
// This will have the values retrieved from the json config files.
_productApiSettings = productsApiSettings.Value;
}
public IActionResult Index()
{
// Using properties from the settings
var productApiAuthURL = _productApiSettings.BaseUrl + _productApiSettings.AuthEndpoint;
return View();
}
}
I hope this will help you solve your issue.