如何使用构造函数参数,其值存储在 appsettings.json
中?
services.AddTransient<IService, Service>(x => new Service("arg1", "arg2"));
我使用IOptions
接口(interface)来读取我的配置值
services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));
最佳答案
如果使用 IOptions<T>
然后更新Service
显式依赖 IOptions<MyOptions>
的构造函数以便它可以被注入(inject)到类中。
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
}
}
如果无法更改服务类构造函数,则在对象工厂委托(delegate)中解析选项
services.AddTransient<IService, Service>(serviceProvider => {
var options = serviceProvider.GetService<IOptions<MyOptions>>();
return new Service(options.Value.arg1, options.Value.arg2);
});
关于c# - .NET Core 2 和 DI - 在构造函数中使用 appsettings.json 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508907/