在一个 .NET Core 控制台程序中需要读取环境变量的值,想借助 .NET Core Generic Host 读取,请问如何实现?
通过下面的代码实现了
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using System;
namespace Cnblogs.Question
{
class Program
{
static void Main(string[] args)
{
var host = new HostBuilder()
.ConfigureAppConfiguration((context, configApp) =>
{
configApp.AddEnvironmentVariables();
}).Build();
var conf = host.Services.GetRequiredService<IConfiguration>();
Console.WriteLine(conf["conn"]);
}
}
}
需要安装的 nuget 包
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.0" />
正想发demo