03C# 从命令行或环境变量读取配置

发布时间 2023-12-14 09:52:58作者: 落花流水1173

前面几篇文章主要讲解读取Json文件,这篇文章讲解如何通过命令行和环境变量读取配置

安装Nuget包:Micosoft.Extensions.Configuration.CommandLine(命令行读取)

安装Nuget包:Micosoft.Extensions.Configuration.EnvironmentVariables(环境变量读取)

配置命令行参数:

 配置环境变量参数:

 

扁平化配置:对于像命令行参数和环境变量输入等简单的键值结构,如何需要配置复杂嵌套的数据结构,需要对数据进行扁平化处理
1)层级结构属性:使用A:B:C
2)层级结构数组:使用A:B:0,A:B:1,。。。(0,1,2代表集合索引)

添加与配置相对应的实体类

 public class WebConfig
 {
     public string Name { get; set; }
     public string Age { get; set; }

     public Proxy Proxy { get; set; }

     public override string ToString()
     {
         return $"Name:{Name},Age:{Age},{Proxy.ToString()}";
     }
 }

 public class Proxy
 {
     public string Address { get; set; }
     public string Port { get; set; }

     public List<int> Ids { get; set; } = new List<int>();

     public override string ToString()
     {
         string str = null;
         for (int i = 0; i < Ids.Count; i++)
         {
             str += "Id" + i + "=" + Ids[i];
         }
         return $"Address:{Address},Port:{Port},{str}";
     }
 }

Test1Mode是注入了Proxy的实体类,Test2Mode是注入了WebConfig的实体类

 public class Test1Model
 {
     private readonly IOptionsSnapshot<Proxy> optionsSnapshot;

     public Test1Model(IOptionsSnapshot<Proxy> optionsSnapshot)
     {
         this.optionsSnapshot = optionsSnapshot;
     }

     public void Test()
     {
       Proxy proxy=  this.optionsSnapshot.Value;
         Console.WriteLine(proxy.ToString());
        
     }
 }

 public class Test2Model
 {
     private readonly IOptionsSnapshot<WebConfig> _snapshot;

     public Test2Model(IOptionsSnapshot<WebConfig> snapshot)
     {
         _snapshot = snapshot;
     }
     public void Test()
     {
         WebConfig config = _snapshot.Value;
         Console.WriteLine(config.ToString()) ;
     }
 }

Main方法如下:

 static void Main(string[] args)
 {
     ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
     //configurationBuilder.AddCommandLine(args);
     configurationBuilder.AddEnvironmentVariables();
     IConfigurationRoot config=configurationBuilder.Build();

     ServiceCollection services = new ServiceCollection();
     services.AddScoped<Test1Model>();
     services.AddScoped<Test2Model>();

     services.AddOptions().Configure<Proxy>(options => config.GetSection("Proxy").Bind(options));
     services.AddOptions().Configure<WebConfig>(e=>config.Bind(e));

     using(var service = services.BuildServiceProvider())
     {
       var test1=  service.GetRequiredService<Test1Model>();
         test1.Test();

         var test2=service.GetRequiredService<Test2Model>();
         test2.Test();
     }


     
     
 }

总结,命令行读取和环境变量读取与上篇文章Json读取主要的差别是,安装的nuget包不同,数据的配置不同,然后在主函数中,

命令行通过:configurationBuilder.AddCommandLine(args);

环境变量通过: configurationBuilder.AddEnvironmentVariables();

其它并没有什么区别