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

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)

Nko*_*osi 6

如果使用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)

ASP.NET Core中的参考选项模式

  • "IOptions <T>"是不必要的,因为OP使用了`services.Configure`.这意味着他们现在可以直接注入"MyOptions".注入`IOptionsSnapshot <T>`有好处,因为它可以让你重新加载功能,但鉴于OP正在添加一个瞬态服务,无论如何,即使这是多余的. (2认同)