9:命令行配置提供程序-.NET Core开发实战
.NET Core开发实战前文传送门:
- 第1课:课程介绍
- 第2课:内容综述
- 第3课:.NET Core的现状、未来以及环境搭建
- 第4课:Startup:掌握ASP.NET Core的启动过程
- 第5课:依赖注入:良好架构的起点(上)
- 第5课:依赖注入:良好架构的起点(中)
- 第5课:依赖注入:良好架构的起点(下)
- 第6课:作用域与对象释放行为(上)
- 第6课:作用域与对象释放行为(下)
- 第7课:用Autofac增强容器能力(上)
- 第7课:用Autofac增强容器能力(下)
- 第8课:配置框架:让服务无缝适应各种环境
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); #endregion var 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

原文出处:微信公众号【DotNet NB】,作者【郑子铭】
原文链接:https://mp.weixin.qq.com/s/kyaTuVeEyUCNvYTrfY5IFQ
本文观点不代表Dotnet9立场,转载请联系原作者。