Raf*_*ski 4 c# application-settings asp.net-core-3.1
假设我们有这样的 AppSettings.json
{
"Region": Europe,
"WeirdService": {
"JustField": "value"
}
}
Run Code Online (Sandbox Code Playgroud)
在单独的单例类中注册WeirdService设置(或使用选项模式)很好,只需:
service.AddSingleton(configuration.GetSection("WeirdService").Get<WeirdService>();
Run Code Online (Sandbox Code Playgroud)
此时就可以了。然而,我不知道如何像我的示例中那样干净地处理这个顶级属性Region。
我知道我可以直接注入IConfiguration和使用config.GetValue<string>("Region")或直接访问配置,但我想知道是否有一些干净、更好的方法,无需在服务中对这些东西进行硬编码。
我忘了提及。我目前合作的团队使用 .NET Core 3.1,因为它是当前的 LTS 版本。
小智 5
我认为最简单的方法是为顶级键创建一个类。在您的情况下,您可以使用单个属性 Region 创建类似 AppConfig 的内容。然后,您只需注册它,而无需使用 Configuration 对象获取配置节,Configure 方法无论如何都需要 Configuration 接口,而不是 ConfigurationSection。
应用程序配置:
public class AppConfig
{
public string? Region { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
登记:
public static IServiceCollection AddOptions(this IServiceCollection services, IConfiguration configuration)
{
return services.Configure<AppConfig>(configuration);
}
Run Code Online (Sandbox Code Playgroud)
用法:
public class ExampleConsumer
{
public ExampleConsumer(IOptions<AppConfig> appConfig) {}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3694 次 |
| 最近记录: |