.net core 3.1 服务承载【配置文件】 电脑版发表于:2021/2/7 10:06 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 3.1 服务承载【配置文件】 [TOC] 目录 ------------ tn>https://www.tnblog.net/hb/article/details/5591 内容 ------------ tn>在不同的环境需要有不同,配置文件进行环境的配置,下面我们添加两个环境配置。 ![](https://img.tnblog.net/arcimg/hb/8d55e1e833124c9eaeadc60f5ed20fad.png) ![](https://img.tnblog.net/arcimg/hb/0de8291f0adf455097d19d195482963d.png) >`appsettings.production.json` ```json { "MetricsCollection": { "DeliverTo": { "Host": "192.168.0.1", "Port": "22" } } } ``` >`appsettings.stagin.json` ```json { "MetricsCollection": { "DeliverTo": { "Host": "192.168.0.2", "Port": "22" } } } ``` tn>最后在`HostBuilder`中添加命令行参数的接收,并通过不同的环境变量名加载不同的环境文件。 ```csharp var fakeMetricsCollector = new FakeMetricsCollector(); new HostBuilder() // 获取命令行的参数 .ConfigureHostConfiguration(builder=>builder.AddCommandLine(args)) .ConfigureAppConfiguration((context,builder)=>builder .AddJsonFile("appsetting.json",false) // 添加不同环境的json .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json",true) ) .ConfigureServices((context,svcs) => svcs .AddSingleton<IProcessorMetricsCollector>(fakeMetricsCollector) .AddSingleton<INetworkMetricsCollector>(fakeMetricsCollector) .AddSingleton<IMemoryMetricsCollector>(fakeMetricsCollector) .AddSingleton<IMetricsDeliverer, FakeMetricsDeliverer>() .AddSingleton<IHostedService, PerformanceMetricsCollector>() // 添加配置 .AddOptions() .Configure<MetricsCollectionOptions>(context.Configuration.GetSection("MetricsCollection")) ) .Build() .Run(); ``` ![](https://img.tnblog.net/arcimg/hb/771cf60939b746e2ab8f02b871b6a2c5.png)