.NET Core 5 Console 泛用主機 依照環境變數讀取對應設定檔 AppSetting

筆記下 Console 達到如同 Web Application 讀取設定檔

.Net 3.0 以後環境變數名稱規則變更如下所示

  • Console => DOTNET_ENVIRONMENT
  • Web => ASPNETCORE_ENVIRONMENT
    (值會覆寫 DOTNET_ENVIRONMENT)

.Net 3.0 以前環境變數名稱皆為 ASPNETCORE_ENVIRONMENT

NEW

開一個全新的 .Net Core Console 專案

Nuget

  • Microsoft.Extensions.Hosting
  • Microsoft.Extensions.Hosting.Abstractions
  • Microsoft.Extensions.Configuration.Abstractions

Code

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp1
{
    class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<AlbertService>();
                })
                .ConfigureAppConfiguration((builderContext, config) =>
                {
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddJsonFile(
                            $"appsettings.{builderContext.HostingEnvironment.EnvironmentName}.json"
                            , optional: true, reloadOnChange: true);
                });
    }
}

Service

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp1
{
    
    public class TestService:IHostedService
    {
        private readonly IConfiguration Configuration;

        public TestService(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine(Configuration["MyKey"]);
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine(Configuration["MyKey"]);
        }
    }
}

appsettings.Test.json (記得屬性要改成 Always Copy 不然會找不到檔案)

{
  "MyKey": "測試值",
}

launchSettings.json

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "ConsoleApp1": {
      "commandName": "Project",
      "environmentVariables": {
        "DOTNET_ENVIRONMENT": "Test"
      }
    }
  }
}

※ .Net 3.0 以上環境變數為 DOTNET_ENVIRONMENT

參照

https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-5.0#app-configuration

PS5