[英].NET Core 2 & DI - use values from appsettings.json in the constructor?
how to use the constructor parameters, whose values are stored in the appsettings.json
? 如何使用构造函数参数,其值存储在
appsettings.json
?
services.AddTransient<IService, Service>(x => new Service("arg1", "arg2"));
I use the IOptions
interface to read my config values 我使用
IOptions
接口来读取我的配置值
services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));
If using IOptions<T>
then update Service
constructor to explicitly depend on IOptions<MyOptions>
so that it can be injected into the class. 如果使用
IOptions<T>
则更新Service
构造函数以显式依赖于IOptions<MyOptions>
以便将其注入到类中。
public class Service: IService {
public Service(IOptions<MyOptions> options) {
this.arg1 = options.Value.arg1;
this.arg2 = options.Value.arg2;
}
}
Configuration can be simplified to 配置可以简化为
services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));
services.AddTransient<IService, Service>();
Assuming appsettings.json contains 假设appsettings.json包含
{
"MyOptions": {
"arg1": value1,
"arg2": value2
}
}
If unable to change service class constructor then resolve option in object factory delegate 如果无法更改服务类构造函数,则解析对象工厂委托中的选项
services.AddTransient<IService, Service>(serviceProvider => {
var options = serviceProvider.GetService<IOptions<MyOptions>>();
return new Service(options.Value.arg1, options.Value.arg2);
});
Reference Options pattern in ASP.NET Core ASP.NET Core中的参考选项模式
The parameter in the lambda for that overload of AddTransient
you're using is actually an instance of IServiceProvider
. lambda中用于您正在使用的
AddTransient
重载的参数实际上是IServiceProvider
一个实例。 That means you can simply do: 这意味着你可以简单地做:
services.AddTransient<IService, Service>(p => {
var options = p.GetRequiredService<MyOptions>();
return new Service(options.arg1, options.arg2);
});
You can get the values from appsettings.json with the frameworks IConfiguration interface. 您可以使用框架IConfiguration接口从appsettings.json获取值。
Lets say your json is 让我们说你的json是
{
"argSection":
{
"arg1": 1,
"arg2": 2
}
}
Then read the values like this 然后读取这样的值
services.AddTransient<IService, Service>(x => new Service(Configuration["argSection:arg1"], Configuration["argSection:arg2"]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.