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

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

如何使用构造函数参数,其值存储在 appsettings.json 中?

services.AddTransient<IService, Service>(x => new Service("arg1", "arg2"));

我使用IOptions 接口(interface)来读取我的配置值

services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));

最佳答案

如果使用 IOptions<T>然后更新Service显式依赖 IOptions<MyOptions> 的构造函数以便它可以被注入(inject)到类中。

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
    }
}

如果无法更改服务类构造函数,则在对象工厂委托(delegate)中解析选项

services.AddTransient<IService, Service>(serviceProvider => {
    var options = serviceProvider.GetService<IOptions<MyOptions>>();
    return new Service(options.Value.arg1, options.Value.arg2);
});

引用 Options pattern in ASP.NET Core

关于c# - .NET Core 2 和 DI - 在构造函数中使用 appsettings.json 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508907/

相关文章:

c# - C# 中的编程构建事件?

dependency-injection - 使用来自请求的信息的 AddTransient 服务

c# - ASP.Net Core 2 中的全局变量

c# - 限制 Selenium FindElement() 的超时时间

c# - 在 C# 中更改辅助监视器屏幕分辨率

asp.net-core - 从 ASP.NET 5 调用 ADODB COM 对象

c# - 为什么ASP Net Core 2.2不释放内存?

c# - asp.net-core2.0 用户在 20-30 分钟后自动注销

c# - 在 APS.NET Core 2 应用程序中使用(并强制执行)HTTPS

c# - 在datagridview c#中更改搜索关键字的颜色