.NET Core控制台应用程序,如何在每个环境中配置appSettings?

编程入门 行业动态 更新时间:2024-10-28 09:17:21
本文介绍了.NET Core控制台应用程序,如何在每个环境中配置appSettings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个.NET Core 1.0.0控制台应用程序和两个环境。我需要能够根据我设置的环境变量使用 appSettings.dev.json 和 appSettings.test.json 在运行时。通过依赖项注入,IHostingEnvironment和EnvironmentName env,这对于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)?

谢谢。

推荐答案

这是我们在 core 控制台应用程序中执行的操作。此处的关键是在项目中包含正确的依赖项(即(可能不是全部,根据您的需要检查)并复制到输出作为您的 buildoptions

This is how we do it in our core 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?

本文发布于:2023-11-15 12:26:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1594427.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   应用程序   环境   在每个   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!