.NET Core开发实战课程备忘(6) -- 命令行配置提供程序:最简单快捷的配置注入方法
命令行参数支持的格式
- 无前缀的
key=value
模式
- 双中横线
--key=value
或--key value
模式
- 正斜杠
/key=value
或/key value
模式
- 备注:等号分隔符和空格分隔符不能混用*
命令替换模式
- 必须以单横线
-
或双横线--
开头
- 映射字典不能包含重复key
- 主要作用是命令缩写的作用
代码示例
创建项目
创建名字为ConfigurationCommandLineDemo
的控制台应用
,通过nuget
引入以下三个包:
1 2 3
| Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.Abstractions Microsoft.Extensions.Configuration.CommandLine
|
测试支持命令行参数的三种格式
修改Program.Main
方法,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| using System; using System.Collections.Generic; using Microsoft.Extensions.Configuration;
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.WriteLine($"CommandLineKey3:{configurationRoot["CommandLineKey3"]}"); Console.ReadKey(); } } }
|
配置测试参数:
- 在
Visual Studio 2019
中,可以右键项目名称->属性->调试->应用程序参数中输入以下内容:1
| CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3
|
- 在
Visual Studio Code
中,可以编辑launchSettings.json
文件,新增commandLineArgs
字段,具体代码如下:1 2 3 4 5 6 7 8
| { "profiles": { "ConfigurationCommandLineDemo": { "commandName": "Project", "commandLineArgs": "CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3" } } }
|
运行项目,可以看到控制台打印出对应的键值对,类似以下信息:
1 2 3
| CommandLineKey1:value1 CommandLineKey2:value2 CommandLineKey3:value3
|
测试命令替换
为Program.Main
方法添加命令替换映射,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| using System; using System.Collections.Generic; using Microsoft.Extensions.Configuration;
namespace ConfigurationCommandLineDemo { class Program { static void Main(string[] args) { var builder = new ConfigurationBuilder(); var mapper = new Dictionary<string, string>() {{"-k1", "CommandLineKey1"}}; builder.AddCommandLine(args, mapper); var configurationRoot = builder.Build(); Console.WriteLine($"CommandLineKey1:{configurationRoot["CommandLineKey1"]}"); Console.WriteLine($"CommandLineKey2:{configurationRoot["CommandLineKey2"]}"); Console.WriteLine($"CommandLineKey3:{configurationRoot["CommandLineKey3"]}"); Console.ReadKey(); } } }
|
mapper表示用-k1
这个命令可以代替CommandLineKey1
将应用参数修改为:
1
| CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 -k1=value4
|
运行项目会在控制台打印出以下信息:
1 2 3
| CommandLineKey1:value4 CommandLineKey2:value2 CommandLineKey3:value3
|
可以发现CommandLineKey1
原本的值value1
被后面的-k1
的值value4
所替换了,说明了替换规则生效