c# - .NET Core 2 和 DI - 在构造函数中使用 appsettings.json 中的值?
问题描述
如何使用构造函数参数,其值存储在appsettings.json
?
services.AddTransient<IService, Service>(x => new Service("arg1", "arg2"));
我使用IOptions
界面来读取我的配置值
services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));
解决方案
如果使用IOptions<T>
则更新Service
构造函数以显式依赖,IOptions<MyOptions>
以便可以将其注入到类中。
public class Service: IService {
public Service(IOptions<MyOptions> options) {
this.arg1 = options.Value.arg1;
this.arg2 = options.Value.arg2;
}
}
配置可以简化为
services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));
services.AddTransient<IService, Service>();
假设appsettings.json包含
{
"MyOptions": {
"arg1": value1,
"arg2": value2
}
}
如果无法更改服务类构造函数,则解析对象工厂委托中的选项
services.AddTransient<IService, Service>(serviceProvider => {
var options = serviceProvider.GetService<IOptions<MyOptions>>();
return new Service(options.Value.arg1, options.Value.arg2);
});
ASP.NET Core 中的参考选项模式
推荐阅读
- mountebank - 在多个存根中使用 Mountebank 复制行为
- python - 迭代 json,查看文本文件,如果不存在则追加数据
- r - 如何通过 shell 脚本在浏览器中打开 ggplot/plotly 绘图
- spring-boot - 如何使用默认用户名/密码初始化 Spring Boot 安全配置,但在第二次运行时不会崩溃?
- excel - 为什么我的 VBA 循环给我一个“运行时 13 错误:不匹配”?
- java - 实现一种算法,将盖子与正确大小的罐子相匹配
- c# - 保存 XML 文件时的 UWP C# System.UnauthorizedAccessException
- linux - 如何在系统启动时 logrotate 自定义日志文件
- gdb - 调试mpi程序时如何保持xterm?
- c# - 简单的下拉列表过滤器?