新建一個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
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。