.NET Core 控制台应用程序,如何为每个环境配置 appSettings? [英] .NET Core console application, how to configure appSettings per environment?

查看:42
本文介绍了.NET Core 控制台应用程序,如何为每个环境配置 appSettings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .NET Core 1.0.0 控制台应用程序和两个环境.我需要能够根据我在运行时设置的环境变量使用 appSettings.dev.jsonappSettings.test.json.通过依赖注入和 IHostingEnvironment 以及 EnvironmentName 环境,这对于 ASP.NET Core Web 应用程序来说似乎非常简单.变量,但是我应该如何为控制台应用程序连接东西(除了编写我自己的使用 Microsoft.Framework.Configuration.EnvironmentVariables 的自定义代码)?

I have a .NET Core 1.0.0 console application and two environments. I need to be able to use appSettings.dev.json and appSettings.test.json based on environment variables I set at run time. This seems to be quite straight forward for ASP.NET Core web applications, via dependency injection and IHostingEnvironment and the EnvironmentName env. variable, however how should I wire things up for the console application (besides writing my own custom code that uses Microsoft.Framework.Configuration.EnvironmentVariables)?

谢谢.

推荐答案

这就是我们在 .netcore 控制台应用程序中的做法.这里的关键是在您的项目中包含正确的依赖项(可能不是全部,根据您的需要检查)和复制到输出appSetting.json 作为 buildoptions

This is how we do it in our .netcore console app. The key here is to include the right dependencies on your project namely (may be not all, check based on your needs) and copy to output the appSetting.json as part of your buildoptions

  {
    "buildOptions": {
    "emitEntryPoint": true,
    "copyToOutput": {
       "include": [
       "appsettings*.json",
       "App*.config"
                 ]
          }
},

using Microsoft.Extensions.Configuration;
namespace MyApp
{
    public static void Main(string[] args)
    {
        var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
       

        var builder = new ConfigurationBuilder()
            .AddJsonFile($"appsettings.json", true, true)
            .AddJsonFile($"appsettings.{environmentName}.json", true, true)
            .AddEnvironmentVariables();
        var configuration = builder.Build();
        var myConnString= configuration.GetConnectionString("SQLConn");
    }
}

这篇关于.NET Core 控制台应用程序,如何为每个环境配置 appSettings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆