09 | 命令行配置提供程序:最简单快捷的配置注入方法


支持的命令格式

  • 无前缀的 **key=value** 模式
  • 双中横线模式 **--key==value****--key value**
  • 正斜杠模式 **/key=value**** **或 **/key value**

备注: 等号分隔符和空格分隔符不能混用

命令替换模式

这个模式是指我们可以给我们的命名参数提供别名

  • 必须以(-)单划线或双花线(--)开头
  • 映射字典不能包含重复的Key

新建控制台应用程序??添加包

using Microsoft.Extensions.Configuration;
using System;

namespace ConfigurationCommandLineDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder();
            // 命令配置和入参是由Main函数提供的
            builder.AddCommandLine(args);

            var root = builder.Build();
            Console.WriteLine($"CommandLineKey1 : {root["CommandLineKey1"]}");
            Console.ReadKey();
        }
    }
}

为了演示,我们可以设置我们调试模式启动时的命令参数:
鼠标右键项目??属性??调试??应用程序参数

当然我们也可以通过文件来编辑 launchSettings.json 这个文件

这个文件和属性设置来去配置我们的参数是一样的,本质上就是修改这里的值

然后我们去运行,会发现报错。

因为,凡是单横杠的命令,就意味着它需要去找别名,如果我们没有配置的话,它是会报错的,这里我们把它改成单横杠,就代表是一个普通命令。

最终输出:

接下来我们使用命令替换模式

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;

namespace ConfigurationCommandLineDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder();
            // 命令配置和入参是由Main函数提供的
            //builder.AddCommandLine(args);

            // 命令替换
            var mapper = new Dictionary { { "-k1", "CommandLineKey1" } };
            builder.AddCommandLine(args, mapper);

            var root = builder.Build();
            Console.WriteLine($"CommandLineKey1 : {root["CommandLineKey1"]}");
            Console.WriteLine($"CommandLineKey2 : {root["CommandLineKey2"]}");
            Console.ReadKey();
        }
    }
}

var mapper = new Dictionary { { "-k1", "CommandLineKey1" } };
builder.AddCommandLine(args, mapper);
将命令行参数 --k1 改成单斜杠 -k1
运行:

这个场景是用来做什么的,实际上我们可以看下.NET自己的命令行工具

实际上最典型的场景就是给我们的应用的命令行参数提供一个短命名开解命名的方式。
就比如上图中的-h就等于-help