.NET Core开发实战(第9课:命令行配置提供程序)--学习笔记
09 | 命令行配置提供程序:最簡單快捷的配置注入方法
這一節講解如何使用命令行參數來作為配置數據源
命令行配置(提供程序的)支持三種格式的命令
1、無前綴的 key=value 模式
2、雙中橫線模式 --key=value 或 --key value
3、正橫杠模式 /key=value 或 /key value
備注:等號分隔符和空格分隔符不能混用
命令替換模式:為命令參數提供別名
1、必須以單橫杠(-)或雙橫杠(--)開頭
2、 映射字典不能包含重復 Key
源碼鏈接:
https://github.com/witskeeper/geektime/tree/master/samples/ConfigurationCommandLineDemo
首先引入三個包
Microsoft.Extensions.Configuration.Abstractions
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.CommandLine
主程序
namespace ConfigurationCommandLineDemo {class Program{static void Main(string[] args){var builder = new ConfigurationBuilder();// 把入參傳遞給命令行參提供程序builder.AddCommandLine(args);var configurationRoot = builder.Build();Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}");Console.ReadKey();}} }項目右鍵屬性,設置調試模式啟動時的命令參數
CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 --k1=k3也可以通過文件編輯,launchSettings.json
{"profiles": {"ConfigurationCommandLineDemo": {"commandName": "Project","commandLineArgs": "CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 --k1=k3"}} }啟動程序,輸出如下:
CommandLineKey1:value1 CommandLineKey2:value2接著是命令替換
namespace ConfigurationCommandLineDemo {class Program{static void Main(string[] args){var builder = new ConfigurationBuilder();把入參傳遞給命令行參提供程序//builder.AddCommandLine(args);#region 命令替換var mapper = new Dictionary<string, string> { { "-k1", "CommandLineKey1" } };builder.AddCommandLine(args, mapper);#endregionvar configurationRoot = builder.Build();Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}");Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}");Console.ReadKey();}} }將雙橫杠 --k1=k3 改為 單橫杠 -k1=k3
{"profiles": {"ConfigurationCommandLineDemo": {"commandName": "Project","commandLineArgs": "CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 -k1=k3"}} }啟動程序,輸出如下:
CommandLineKey1:k3 CommandLineKey2:value2可以看出,-k1 替換了 CommandLineKey1 里面的值
這個場景是用來做什么的?
實際上可以看一下 .NET 自己的命令行工具
打開控制臺,輸入 dotnet --help
sdk-options:-d|--diagnostics 啟用診斷輸出。-h|--help 顯示命令行幫助。--info 顯示 .NET Core 信息。--list-runtimes 顯示安裝的運行時。--list-sdks 顯示安裝的 SDK。--version 顯示使用中的 .NET Core SDK 版本。這里可以看到 options 支持雙橫杠長命名和單橫杠的短命名
實際上最典型的場景就是給應用的命令行參數提供了一個短命名快捷命名的方式,比如說 -h 就可以替換 --help
總結
以上是生活随笔為你收集整理的.NET Core开发实战(第9课:命令行配置提供程序)--学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微软推出全新的Windows 10系统图
- 下一篇: gRPC in ASP.NET Core