【转】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
可以看到获取appsettings.json里的值很简单,如果是对象值只需要加一个冒号。
更好的方式去获取一个对象是用IOptions,我们接下来看看。
3. 注入IOptions
先定义一个OptionSample类需要实现IOptions接口:
然后,注入代码很简单
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
这个同样在构造函数里传参数
大家可以看到在NETCore中无处不在的依赖注入。源码参考Github
转 https://blog.csdn.net/u010690818/article/details/106036956/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)