NETCore下IConfiguration和IOptions的用法

新建一个NETCore Web API项目,在Startup.cs里就会开始使用IConfiguration和IOptions了,我们来看看如何使用。
IConfiguration 是用来加载配置值的,可以加载内存键值对、JSON或XML配置文件,我们通常用来加载缺省的appsettings.json .

1. 注入IConfiguration

执行到Startup的时候,IConfiguration已经被注入到services了,不需要我们额外添加注入的代码,缺省就是读取appsettings.json文件,你可以理解在Startup.cs里有隐藏的注入代码类似如下:

var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddEnvironmentVariables();
Configuration = builder.Build();
services.AddSingleton<IConfiguration>(Configuration);

2. 使用IConfiguration

我们先设置一下appsettings.json

{
  "test1":"v1",
  "test2":{
    "key1":"v2",
    "key2":"v3",
    "key3":4,
    "key4":true
  }
}

在Controller里直接在构造函数里传入IConfiguration


 
image.png

可以看到获取appsettings.json里的值很简单,如果是对象值只需要加一个冒号。
更好的方式去获取一个对象是用IOptions,我们接下来看看。

3. 注入IOptions

先定义一个OptionSample类需要实现IOptions接口:


 
image.png

然后,注入代码很简单

services.Configure<OptionSample>(Configuration.GetSection("test2"));

这句话等同于以下代码

OptionSample sample = new OptionSample();
sample.key1 = Configration["test2:key1"];
sample.key2 = Configration["test2:key2"];
sample.key3 = Configration["test2:key3"];
sample.key4 = Configration["test2:key4"];
services.AddSingle<IOptions<OptionSample>>(sample);

4. 使用IOptions

这个同样在构造函数里传参数


 
image.png

大家可以看到在NETCore中无处不在的依赖注入。源码参考Github



作者:voxer
链接:https://www.jianshu.com/p/b9416867e6e6
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2020-03-25 21:50  风雪江山  阅读(5013)  评论(0编辑  收藏  举报