'How to I bind Microsoft.Hosting.Lifetime in my appsettings.json file to my AppSettings class in my C# application?
I'm trying to bind my appsettings.json file to my AppSettings class. It works for all properties except for "Microsoft.Hosting.Lifetime" simply because I don't know how to create a property in a C# class with dots in it.
Here is my appsettings.json file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
...
}
Here is AppSettings.cs:
using System;
using Microsoft.Extensions.Configuration;
namespace AMI.TBoard.LCTransfer
{
public class AppSettings
{
public Logging Logging { get; set; }
public ConnectionStrings ConnectionStrings { get; set; }
public FtpConnectionStrings FtpConnectionStrings { get; set; }
public void BindConfig(IConfiguration config)
{
config.Bind(this);
}
}
public class Logging
{
public LogLevel LogLevel { get; set; }
}
public class LogLevel
{
public string Default { get; set; }
public string Microsoft { get; set; }
}
public class ConnectionStrings
{
public string appDbConnection { get; set; }
}
public class FtpConnectionStrings
{
public string url { get; set; }
public string username { get; set; }
public string password { get; set; }
public string exportFolder { get; set; }
public string importFolder { get; set; }
}
}
Note that all properties in appsettings.json map onto properties by the same name in AppSettings.cs. Nested properties bind to nested classes (I'm not showing the connection string properties in appsettings.json for obvious reasons, but they're there).
Note also that there is no binding to "Microsoft.Hosting.Lifetime". What would I have to add to AppSettings.cs to bind it to "Microsoft.Hosting.Lifetime"?
EDIT: Here is how I do the binding:
In program.cs:
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var appSettings = new AppSettings();
appSettings.BindConfig(config);
In AppSettings, you can see where I bind the configuration above.
Solution 1:[1]
private string _microsoftHostingLifetime;
public string MicrosoftHostingLifetime {
get
{
if (string.IsNullOrWhiteSpace(_microsoftHostingLifetime))
{
_microsoftHostingLifetime = Configuration["Logging:LogLevel:Microsoft.Hosting.Lifetime"];
}
return _microsoftHostingLifetime;
}
set
{
_microsoftHostingLifetime = value;
}
}
I deal by doing like this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ramil Aliyev |
