首页 > 解决方案 > .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)));

标签: c#asp.net-coreasp.net-core-2.0

解决方案


如果使用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 中的参考选项模式


推荐阅读