Ton*_*ony 2 c# asp.net-core asp.net-core-2.0
如何使用构造函数参数,其值存储在appsettings.json?
services.AddTransient<IService, Service>(x => new Service("arg1", "arg2"));
Run Code Online (Sandbox Code Playgroud)
我使用IOptions界面来读取我的配置值
services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));
Run Code Online (Sandbox Code Playgroud)
如果使用IOptions<T>则更新Service构造函数以显式依赖,IOptions<MyOptions>以便可以将其注入到类中.
public class Service: IService {
public Service(IOptions<MyOptions> options) {
this.arg1 = options.Value.arg1;
this.arg2 = options.Value.arg2;
}
}
Run Code Online (Sandbox Code Playgroud)
配置可以简化为
services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));
services.AddTransient<IService, Service>();
Run Code Online (Sandbox Code Playgroud)
假设appsettings.json包含
{
"MyOptions": {
"arg1": value1,
"arg2": value2
}
}
Run Code Online (Sandbox Code Playgroud)
如果无法更改服务类构造函数,则解析对象工厂委托中的选项
services.AddTransient<IService, Service>(serviceProvider => {
var options = serviceProvider.GetService<IOptions<MyOptions>>();
return new Service(options.Value.arg1, options.Value.arg2);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |