重新整理 .net core 實踐篇————配置系統——軍令(命令行)[六]


前言

前文已經基本寫了一下配置文件系統的一些基本原理。本文介紹一下命令行導入配置系統。

正文

要使用的話,引入Microsoft.extensions.Configuration.commandLine 包。

代碼:

IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddCommandLine(args);
var configurationRoot = builder.Build();
Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");
Console.ReadLine();

寫入測試參數:

結果:

另一個問題,就是命令行支持幾種命令格式。

  1. 無前綴模式 key=value 模式

  2. 雙中橫線模式 --key = value 或 --key vlaue

  3. 正斜杠模式 /key=value 或/key value

注:如果--key = value 這種等號模式,那么就不能使用--key vlaue 這種中間空格二點模式。
配置:

IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddCommandLine(args);
var configurationRoot = builder.Build();
Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");
Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}");
Console.WriteLine($"CommandLineKey3:{configurationRoot["CommandLineKey3"]}");
Console.ReadLine();

結果:

這里其實項目屬性在lauchSettings.json 中,后面我就不截圖,直接放這個啟動配置。

命令替換模式:

{
  "profiles": {
    "ConfigureDemo": {
      "commandName": "Project",
      "commandLineArgs": "CommandLineKey1=value1 /CommandLineKey2=value2 --CommandLineKey3=value3 -k1=value4"
    }
  }
}

代碼:

IConfigurationBuilder builder = new ConfigurationBuilder();
var mappers = new Dictionary<string, string>
{
	{"-k1","CommandLineKey1" }
};
builder.AddCommandLine(args, mappers);
var configurationRoot = builder.Build();
Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");
Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}");
Console.WriteLine($"CommandLineKey3:{configurationRoot["CommandLineKey3"]}");
Console.ReadLine();

這里面就是以-k1的值替換了CommandLineKey1的值。

上述的-k1也不是隨便命名的,要用-開頭才可以替換。

那么這種有什么用呢?

這種可以縮短命名。

{
  "profiles": {
    "ConfigureDemo": {
      "commandName": "Project",
      "commandLineArgs": "-k1=value4"
    }
  }
}

代碼:

IConfigurationBuilder builder = new ConfigurationBuilder();
var mappers = new Dictionary<string, string>
{
	{"-k1","CommandLineKey1" }
};
builder.AddCommandLine(args, mappers);
var configurationRoot = builder.Build();
Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");
Console.ReadLine();

結果:

下一節配置系統之變色龍(環境配置)

上述為個人整理,如有錯誤望請指出,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM