繁体   English   中英

.NET Core 2和DI - 在构造函数中使用appsettings.json中的值?

[英].NET Core 2 & DI - use values from appsettings.json in the constructor?

如何使用构造函数参数,其值存储在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中的参考选项模式

lambda中用于您正在使用的AddTransient重载的参数实际上是IServiceProvider一个实例。 这意味着你可以简单地做:

services.AddTransient<IService, Service>(p => {
    var options = p.GetRequiredService<MyOptions>();
    return new Service(options.arg1, options.arg2);
});

您可以使用框架IConfiguration接口从appsettings.json获取值。

让我们说你的json是

{
   "argSection": 
    {
       "arg1": 1,
       "arg2": 2
    }
}

然后读取这样的值

services.AddTransient<IService, Service>(x => new Service(Configuration["argSection:arg1"], Configuration["argSection:arg2"]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM