static void Main(string[] args) { var host = new HostBuilder(); // 環境パスのDOTNETCORE_ENVIRONMENTを取得 var environment = Environment.GetEnvironmentVariable("DOTNETCORE_ENVIRONMENT") ?? "Development"; // 環境の設定 host.UseEnvironment(environment); // ホストの構成 host.ConfigureHostConfiguration(config => { // Microsoft.Extensions.Configuration config.SetBasePath(Directory.GetCurrentDirectory()); // Microsoft.Extensions.Configuration.EnvironmentVariables // 環境変数の先頭文字列"EnvironmentSettingModel_"の変数を取り込む. // 取り込んだ環境変数の名前は"EnvironmentSettingModel_"の部分がトリミングされる config.AddEnvironmentVariables(prefix: "EnvironmentSettingModel_"); // Microsoft.Extensions.Configuration.JSON // 環境変数DOTNETCORE_ENVIRONMENTの設定値を使用する。 config.AddJsonFile($"Settings/setting.json"); // 同じ定義は後に読み込んだ方で上書きされる config.AddJsonFile($"Settings/setting.{environment}.json"); // Microsoft.Extensions.Configuration.Ini config.AddIniFile("Settings/setting.ini"); // Microsoft.Extensions.Configuration.XML config.AddXmlFile("Settings/setting.xml"); // Microsoft.Extensions.Configuration.Memory config.AddInMemoryCollection(new Dictionary <string, string>() { { "InMemoryMessage", "Hello InMemoryCollection!" } }); // Microsoft.Extensions.Configuration.CommandLine config.AddCommandLine(args); }); // アプリケーションの構成 host.ConfigureAppConfiguration((hostContext, config) => { var env = hostContext.HostingEnvironment; if (env.IsDevelopment()) { // Microsoft.Extensions.Configuration.UserSecrets config.AddUserSecrets <Program>(); } }); // サービスの構成 host.ConfigureServices((hostContext, config) => { // Microsoft.Extensions.DependencyInjection config.AddHostedService <SampleService>(); // Microsoft.Extensions.Options.ConfigurationExtensions config.Configure <IniSettingModel>(hostContext.Configuration.GetSection("IniSettingModel")); config.Configure <JsonSettingModel>(hostContext.Configuration.GetSection("JsonSettingModel")); config.Configure <XmlSettingModel>(hostContext.Configuration.GetSection("XmlSettingModel")); config.Configure <UserSecretModel>(hostContext.Configuration.GetSection("UserSecretSettingModel")); config.Configure <CommandLineSettingModel>(hostContext.Configuration.GetSection("CommandLineSettingModel")); // こういった方法でも使用可能 var message = hostContext.Configuration.GetValue <String>("UserSecretSettingModel:Message"); var messageModel1 = hostContext.Configuration.GetSection("UserSecretSettingModel").Get <BaseSettingModel>(); var messageModel2 = hostContext.Configuration.GetValue <UserSecretModel>("UserSecretSettingModel"); var messageModel3 = new BaseSettingModel(); hostContext.Configuration.GetSection("UserSecretSettingModel").Bind(messageModel3); }); host.UseConsoleLifetime().Build().Run(); }