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

posted @   dreamw  阅读(276)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示