ASP.NET Core提供了一种方便的方式来绑定嵌套的配置到接口上。以下是一个包含代码示例的解决方法:
public interface IAppSettings
{
DatabaseSettings Database { get; set; }
LoggingSettings Logging { get; set; }
}
public class DatabaseSettings
{
public string ConnectionString { get; set; }
public int Timeout { get; set; }
}
public class LoggingSettings
{
public string LogLevel { get; set; }
}
appsettings.json
配置文件中定义嵌套的配置。{
"AppSettings": {
"Database": {
"ConnectionString": "your-connection-string",
"Timeout": 30
},
"Logging": {
"LogLevel": "Information"
}
}
}
public void ConfigureServices(IServiceCollection services)
{
IConfigurationSection appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure(appSettingsSection);
services.AddSingleton(sp =>
sp.GetRequiredService>().Value);
}
IAppSettings
接口,并使用其中的属性。public class MyService
{
private readonly IAppSettings _appSettings;
public MyService(IAppSettings appSettings)
{
_appSettings = appSettings;
}
public void DoSomething()
{
string connectionString = _appSettings.Database.ConnectionString;
int timeout = _appSettings.Database.Timeout;
string logLevel = _appSettings.Logging.LogLevel;
// 使用配置进行操作...
}
}
通过以上步骤,您就可以将嵌套的配置绑定到接口上,并在应用程序中使用它们。