.NET Core Configuration 配置項知識點一網打盡!

雨太阳發表於2024-06-04

控制檯專案中,演示示例

.NET Core Configuration 配置項知識點一網打盡!

1.自定義 Dictionary Config 記憶體字典模式

dotnet add package Microsoft.Extensions.Configuration

IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(new Dictionary<string, string>()
{
    {"key1","v1"},
    {"key2","v2"},
    {"key3","v3"},
    {"key4:key5","v4-v5"},
}!);
IConfigurationRoot configurationRoot = builder.Build();
IConfiguration config = configurationRoot;

Console.WriteLine(configurationRoot["key1"]);
Console.WriteLine(configurationRoot["key2"]);

IConfigurationSection section = config.GetSection("key4");

Console.WriteLine(section["key5"]);
Console.WriteLine(config["key4:key5"]);
Console.WriteLine(configurationRoot["key4:key5"]);

2. 命令替換模式/提供程式

//dotnet add package Microsoft.Extensions.Configuration.CommandLine
var bulider = new ConfigurationBuilder();

//bulider.AddCommandLine(ages);

#region 命令替換模式/提供程式

var mapper = new Dictionary<string, string>()
{
    {"-k1","CommandLineKey1" }
};
bulider.AddCommandLine(ages, mapper);
//結果就會變為 LineKey:k3
//通常用於 短命名,快捷命名

#endregion

var configurationRoot = bulider.Build();
//屬性--> 除錯裡面設定的啟動引數
Console.WriteLine($"LineKey:{configurationRoot["CommandLineKey1"]}");
Console.WriteLine($"LineKey:{configurationRoot["CommandLineKey2"]}");

Console.ReadKey();

3.環境變數提供應用程式

//dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables
var builder = new ConfigurationBuilder();
builder.AddEnvironmentVariables();


var configurationRoot = builder.Build();
//屬性--> 除錯裡面 設定的環境變數的 引數
Console.WriteLine($"key1:{configurationRoot["key1"]}");

#region 分層鍵
Console.WriteLine($"key3:{configurationRoot.GetSection("select")["key3"]}");
Console.WriteLine($"key4:{configurationRoot.GetSection("select:key3")["key4"]}");
#endregion

#region 字首過濾
builder.AddEnvironmentVariables("cy_");
configurationRoot = builder.Build();
Console.WriteLine($"cy key1:{configurationRoot["key1"]}");
#endregion

4.檔案配置提供程式

//dotnet add package Microsoft.Extensions.Configuration.Ini
//dotnet add package Microsoft.Extensions.Configuration.Json
//dotnet add package Microsoft.Extensions.Configuration.NewtonsoftJosn
//dotnet add package Microsoft.Extensions.Configuration.Xml
//dotnet add package Microsoft.Extensions.Configuration.UserSecrets

var builder = new ConfigurationBuilder();
//optional:false 檢測檔案存不存在 預設false,當是true的時候,如果檔案不存在則會報錯~
//reloadOnChange 是否讀取檔案變更
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.AddIniFile("appsettings.ini", optional: false, reloadOnChange: true);
var configurationRoot = builder.Build();

Console.WriteLine($"key1:{configurationRoot["key1"]}");
Console.WriteLine($"key2:{configurationRoot["key2"]}");
Console.WriteLine($"key3:{configurationRoot["key3"]}");
Console.ReadKey();


Console.WriteLine($"key1:{configurationRoot["key1"]}");
Console.WriteLine($"key2:{configurationRoot["key2"]}");
Console.WriteLine($"key3:{configurationRoot["key3"]}");



var connectionString = configurationRoot["DatabaseSettings:ConnectionString"];
var logLevel = configurationRoot["Logging:LogLevel"];
var apiKey = configurationRoot["ApiSettings:ApiKey"];

Console.WriteLine($"Connection String: {connectionString}");
Console.WriteLine($"Log Level: {logLevel}");
Console.WriteLine($"API Key: {apiKey}");

Console.ReadKey();

5.配置變更監聽

var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var configurationRoot = builder.Build();

IChangeToken changeToken = configurationRoot.GetReloadToken();

//注意:Debug 模式下在 \bin\Debug\net8.0\的生成檔案下去修改檔案內容 才生效!!!

////只能獲取一次變更!
//changeToken.RegisterChangeCallback(state =>
//{
//    Console.WriteLine($"key1---->:{configurationRoot["key1"]}");
//    Console.WriteLine($"key2---->:{configurationRoot["key2"]}");
//    Console.WriteLine($"key3---->:{configurationRoot["key3"]}");
//}, configurationRoot);


//多次變更都能捕獲到!
ChangeToken.OnChange(() => configurationRoot.GetReloadToken(), () =>
{
    Console.WriteLine($"key1---->:{configurationRoot["key1"]}");
    Console.WriteLine($"key2---->:{configurationRoot["key2"]}");
    Console.WriteLine($"key3---->:{configurationRoot["key3"]}");
});

Console.ReadKey();

6.配置繫結

//dotnet add package Microsoft.Extensions.Configuration.Binder
//1.繫結已有物件
//2.繫結私有屬性
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var config = new AppSettingConfigModel()
{
    Key1 = "Key1",
    Key2 = "Key2",
    //Key4 = 4
};
var configurationRoot = builder.Build();
configurationRoot.Bind(config); //以appsettings.json 的為準

//多級設定
configurationRoot.GetSection("OrderService").Bind(config, options =>
{
    //private 的私有屬性,也可以賦值進去
    options.BindNonPublicProperties = true;
});

Console.WriteLine($"Key2---->:{config.Key1}");
Console.WriteLine($"Key2---->:{config.Key2}");
Console.WriteLine($"Key4---->:{config.Key4}");

WebApi專案中,演示示例

.NET Core Configuration 配置項知識點一網打盡!
WebApplicationConfig專案
  • Startup.cs 基礎項

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

7.結合IOption<> 使用 選項框架

//繫結整個 appsettings.json 到 AppSettings 類
services.Configure<ConfigOptionsModel>(Configuration);

private readonly IOptionsMonitor<ConfigOptionsModel> _options;

//IOptionsSnapshot
//IOptionsMonitor (單例的時候拿到變更項)
public WeatherForecastController(IOptionsMonitor<ConfigOptionsModel> options)
{
    _options = options;

    _options.OnChange(option =>
    {
        Console.WriteLine($"change-->{option.key1}");
    });
}

[HttpGet]
public string Get()
{
    Console.WriteLine(_options.CurrentValue.key1);
    Console.WriteLine(_options.CurrentValue.key2);
    Console.WriteLine(_options.CurrentValue.key3);
    Console.WriteLine(_options.CurrentValue.key4);
    return "1";
}

8.為選項框架新增驗證邏輯


//為選項框架新增驗證邏輯
services.AddOptions<ConfigOptionsModel>().Configure(op =>
{
    Configuration.Bind(op);
})

////屬性設定驗證 [Range(1,200)]
//.ValidateDataAnnotations();


//自定義屬性驗證 ConfigOptionsVaildateOptions
.Services.AddSingleton<IValidateOptions<ConfigOptionsModel>, ConfigOptionsVaildateOptions>();

////自定義設定
//.Validate(x =>
//{
//    return x.key4 <= 200;
//}, "key4 不能大於200");

//動態設定引數
services.PostConfigure<ConfigOptionsModel>(option =>
{
    option.key1 += "===>PostConfigure";
});

namespace WebApplicationConfig 檔案

public class ConfigOptionsModel
{
    public string key1 { get; set; }
    public string key2 { get; set; }
    public string key3 { get; set; }
    [Range(1,500)]
    public int key4 { get; set; }
}

public class ConfigOptionsVaildateOptions : IValidateOptions<ConfigOptionsModel>
{
    public ValidateOptionsResult Validate(string name, ConfigOptionsModel options)
    {
        if (options.key4 > 300) 
        {
            throw new ValidationException("key4 不能大於300");
        }
        return ValidateOptionsResult.Success;
    }
}

參考專案地址

  • • https://github.com/goodluckily/ConsoleAppConfig

  • • https://github.com/goodluckily/WebApplicationConfig

END 歡迎關注 "ShareFlow" 公眾號
.NET Core Configuration 配置項知識點一網打盡!

相關文章