.net 如何为多个构建配置选择不同的 app.config

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8082662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:01:20  来源:igfitidea点击:

How to select different app.config for several build configurations

.netvisual-studioconfigurationcontinuous-integrationrelease-management

提问by oleksii

I have a dll-type projectthat contains MSTest integration tests. On my machine the tests pass, and I want the same to happen on a CI server (I use TeamCity). But the tests fail, because I need to tweak some settings in app.config. This is why I was thinking to have a separate second app.config file that will hold the settings for CI server.

我有一个包含 MSTest 集成测试的dll 类型项目。在我的机器上测试通过,我希望在 CI 服务器上也能发生同样的事情(我使用 TeamCity)。但是测试失败了,因为我需要调整 app.config 中的一些设置。这就是为什么我想有一个单独的第二个 app.config 文件来保存 CI 服务器的设置。

So I would like to have

所以我想拥有

/Sln
 /Proj
  app.config (I think this is required by VS)
  app.Release.config (This is a standalone independent config file)

Thus if I select Release configuration in build config on CI, I would like to use app.Release.config file instead of app.config

因此,如果我在 CI 的构建配置中选择发布配置,我想使用 app.Release.config 文件而不是 app.config

Problem
This doesn't seem to be straightforward for simple .dll type projects. For web projects, I can do web config transformations. I found a hack how to do these transformations for a dll type project, but I am not a big fan of hacks.

问题
对于简单的 .dll 类型项目来说,这似乎并不简单。对于 Web 项目,我可以进行 Web 配置转换。我找到了一个 hack 如何为 dll 类型的项目进行这些转换,但我不是 hack 的忠实粉丝。

Question
What is a standard approach to tweak app.config files depending on build config for .NET projects (such as Debug, Release, ...)?

问题
根据 .NET 项目(例如 Debug、Release 等)的构建配置调整 app.config 文件的标准方法是什么?

回答by oleksii

Use SlowCheetahplugin. For more options and details of how to use SlowCheetah keep reading.

使用SlowCheetah插件。有关如何使用 SlowCheetah 的更多选项和详细信息,请继续阅读。

As you have already noticed, there is no default and easy way to use different config files for a Library type (.dll)project. The reason is that the current thinking is: "You don't need to"! Framework developers reckon you need configuration for the executable file: be it a console, desktop, web, mobile app or something else. If you start providing configuration for a dll, you may end up with something I can call a config hell. You may no longer understand (easily) why this and that variables have such weird values coming seemingly from nowhere.

正如您已经注意到的,对于库类型 (.dll)项目,没有默认且简单的方法来使用不同的配置文件。原因是现在的想法是:“你不需要”!框架开发人员认为您需要对可执行文件进行配置:无论是控制台、桌面、Web、移动应用程序还是其他东西。如果您开始为dll提供配置,您最终可能会得到一些我可以称之为配置地狱的东西。您可能不再(容易地)理解为什么这个和那个变量有如此奇怪的值,这些值似乎无处可去。

"Hold on", - you may say, "but I need this for my integration/unit testing, and it isa library!". And that is true and this is what you can do (pick only one, don't mix):

“等一下”,-您可能会说,“但我的集成/单元测试需要它是一个库!”。这是真的,这就是你可以做的(只选一个,不要混合):

1. SlowCheetah - transforms current config file

1. SlowCheetah - 转换当前配置文件

You can install SlowCheetah- a Visual Studio plug-in that does all low level XML poking (or transformation) for you. The way it works, briefly:

您可以安装SlowCheetah- 一个 Visual Studio 插件,可为您执行所有低级 XML 探查(或转换)。它的工作方式,简而言之:

  • Install SlowCheetah and restart Visual Studio (Visual Studio > Tools > Extensions and Updates ... > Online > Visual Studio Gallery > search for "Slow Cheetah" )
  • Define your solution configurations (Debugand Releaseare there by default), you can add more (right click on the solution in Solution Explorer> Configuration Manager...> Active Solution Configuration> New...
  • Add a config file if needed
  • Right click on config file > Add Transform
    • This will create Transformation files - one per your configuration
    • Transform files work as injectors/mutators, they find needed XML code in the original config file and inject new lines or mutate needed value, whatever you tell it to do
  • 安装 SlowCheetah 并重新启动 Visual Studio(Visual Studio > Tools > Extensions and Updates ... > Online > Visual Studio Gallery > search for "Slow Cheetah" )
  • 定义您的解决方案配置(默认情况下为调试发布),您可以添加更多(在解决方案资源管理器中右键单击解决方案>配置管理器...>活动解决方案配置>新建...
  • 如果需要,添加配置文件
  • 右键单击配置文件 >添加转换
    • 这将创建转换文件 - 每个配置一个
    • 转换文件作为注入器/修改器工作,它们在原始配置文件中找到所需的 XML 代码并注入新行或改变所需的值,无论你告诉它做什么

2. Fiddle with .proj file - copy-renames a whole new config file

2. 修改 .proj 文件 - 复制重命名一个全新的配置文件

Originally taken from here. It's a custom MSBuild task that you can embed into Visual Studio .projfile. Copy and paste the following code into the project file

最初取自这里。这是一个自定义 MSBuild 任务,您可以将其嵌入到 Visual Studio .proj文件中。将以下代码复制并粘贴到项目文件中

<Target Name="AfterBuild">
    <Delete Files="$(TargetDir)$(TargetFileName).config" />
    <Copy SourceFiles="$(ProjectDir)\Config\App.$(Configuration).config"
          DestinationFiles="$(TargetDir)$(TargetFileName).config" />
</Target>

Now create a folder in the project called Configand add new files there: App.Debug.config, App.Release.configand so on. Now, depending on your configuration, Visual Studio will pick the config file from a Configfolder, and copy-rename it into the output directory. So if you had PatternPA.Test.Integrationproject and a Debugconfig selected, in the output folder after the build you will find a PatternPA.Test.Integration.dll.configfile which was copied from Config\App.Debug.configand renamed afterwards.

现在在名为的项目中创建一个文件夹并在其中Config添加新文件:App.Debug.configApp.Release.config等。现在,根据您的配置,Visual Studio 将从文件Config夹中选择配置文件,并将其复制重命名到输出目录中。因此,如果您选择了PatternPA.Test.Integration项目和调试配置,则在构建后的输出文件夹中,您将找到一个PatternPA.Test.Integration.dll.config文件,该文件随后被复制并重Config\App.Debug.config命名。

These are some notes you can leave in the config files

这些是您可以留在配置文件中的一些注释

<?xml version="1.0" encoding="utf-8"?>
<configuration>

    <!-- This file is copied and renamed by the 'AfterBuild' MSBuild task -->

    <!-- Depending on the configuration the content of projectName.dll.config 
        is fully substituted by the correspondent to build configuration file 
        from the 'Config' directory. -->

</configuration>

In Visual Studio you can have something like this

在 Visual Studio 中你可以有这样的东西

Project structure

项目结构

3. Use scripting files outside Visual Studio

3. 在 Visual Studio 之外使用脚本文件

Each build tool (like NAnt, MSBuild) will provide capabilities to transform config file depending on the configuration. This is useful if you build your solution on a build machine, where you need to have more control on what and how you prepare the product for release.

每个构建工具(如NAntMSBuild)都将提供根据配置转换配置文件的功能。如果您在构建机器上构建解决方案,这将非常有用,您需要在构建机器上更好地控制准备发布产品的内容和方式。

For example you can use web publishing dll's task to transform any config file

例如,您可以使用 Web 发布 dll 的任务来转换任何配置文件

<UsingTask AssemblyFile="..\tools\build\Microsoft.Web.Publishing.Tasks.dll"
    TaskName="TransformXml"/>

<PropertyGroup>
    <!-- Path to input config file -->  
    <TransformInputFile>path to app.config</TransformInputFile>
    <!-- Path to the transformation file -->    
    <TransformFile>path to app.$(Configuration).config</TransformFile>
    <!-- Path to outptu web config file --> 
    <TransformOutputFile>path to output project.dll.config</TransformOutputFile>
</PropertyGroup>

<Target Name="transform">
    <TransformXml Source="$(TransformInputFile)"
                  Transform="$(TransformFile)"
                  Destination="$(TransformOutputFile)" />
</Target>

回答by VHaravy

You can try the following approach:

您可以尝试以下方法:

  1. Right-click on the project in Solution Explorer and select Unload Project.
  2. The project will be unloaded. Right-click on the project again and select Edit <YourProjectName>.csproj.
  3. Now you can edit the project file inside Visual Studio.
  4. Locate the place in *.csproj file where your application configuration file is included. It will look like:
  1. 右键单击解决方案资源管理器中的项目并选择Unload Project
  2. 项目将被卸载。再次右键单击该项目并选择Edit <YourProjectName>.csproj
  3. 现在您可以在 Visual Studio 中编辑项目文件。
  4. 在 *.csproj 文件中找到包含应用程序配置文件的位置。它看起来像:
    <ItemGroup>
        <None Include="App.config"/>
    </ItemGroup>
  1. Replace this lines with following:
  1. 将此行替换为以下内容:
    <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
        <None Include="App.Debug.config"/>
    </ItemGroup>

    <ItemGroup Condition=" '$(Configuration)' == 'Release' ">
        <None Include="App.Release.config"/>
    </ItemGroup>

I have not tried this approach to app.configfiles, but it worked fine with other items of Visual Studio projects. You can customize the build process in almost any way you like. Anyway, let me know the result.

我还没有尝试过这种处理app.config文件的方法,但它与 Visual Studio 项目的其他项目一起工作得很好。您几乎可以以任何您喜欢的方式自定义构建过程。无论如何,让我知道结果。

回答by Daniel Dyson

You should consider ConfigGen. It was developed for this purpose. It produces a config file for each deployment machine, based on a template file and a settings file. I know that this doesn't answer your question specifically, but it might well answer your problem.

您应该考虑ConfigGen。它是为此目的而开发的。它基于模板文件和设置文件为每台部署机器生成一个配置文件。我知道这并没有具体回答您的问题,但它可能很好地回答了您的问题。

So rather than Debug, Release etc, you might have Test, UAT, Production etc. You can also have different settings for each developer machine, so that you can generate a config specific to your dev machine and change it without affecting any one else's deployment.

因此,除了 Debug、Release 等,您可能还有 Test、UAT、Production 等。您还可以为每台开发机器设置不同的设置,以便您可以生成特定于您的开发机器的配置并进行更改,而不会影响任何其他人的部署.

An example of usage might be...

使用示例可能是...

<Target Name="BeforeBuild">
    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t       
        $(ProjectDir)App.config.template.xml -o $(SolutionDir)ConfigGen" />

    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t
        $(ProjectDir)App.config.template.xml -l -n $(ProjectDir)App.config" />
</Target>

If you place this in your .csproj file, and you have the following files...

如果你把它放在你的 .csproj 文件中,并且你有以下文件......

$(ProjectDir)App.Config.Settings.xls

MachineName        ConfigFilePath   SQLServer        

default             App.config      DEVSQL005
Test                App.config      TESTSQL005
UAT                 App.config      UATSQL005
Production          App.config      PRODSQL005
YourLocalMachine    App.config      ./SQLEXPRESS


$(ProjectDir)App.config.template.xml 

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=[%SQLServer%]; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

... then this will be the result...

……那么结果就是……

From the first command, a config file generated for each environment specified in the xls file, placed in the output directory $(SolutionDir)ConfigGen

从第一个命令开始,为 xls 文件中指定的每个环境生成一个配置文件,放置在输出目录 $(SolutionDir)ConfigGen

.../solutiondir/ConfigGen/Production/App.config

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=PRODSQL005; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

From the second command, the local App.config used on your dev machine will be replaced with the generated config specified by the local (-l) switch and the filename (-n) switch.

在第二个命令中,您的开发机器上使用的本地 App.config 将替换为由本地 (-l) 开关和文件名 (-n) 开关指定的生成配置。

回答by tem peru

Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :

使用与 Romeo 相同的方法,我将其调整为 Visual Studio 2010 :

 <None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />

 <None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />

Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!

在这里,您需要将两个 App.config 文件保存在不同的目录中(appDebug 和 appRelease)。我测试了它,它工作正常!

回答by Ludwo

I'm using XmlPreprocess toolfor config files manipulation. It is using one mapping file for multiple environments(or multiple build targets in your case). You can edit mapping file by Excel. It is very easy to use.

我正在使用XmlPreprocess 工具进行配置文件操作。它为多个环境(或在您的情况下使用多个构建目标)使用一个映射文件。您可以通过 Excel 编辑映射文件。这是非常容易使用。

回答by Eniola

SlowCheetah and FastKoala from the VisualStudio Gallery seem to be very good tools that help out with this problem.

VisualStudio Gallery 中的SlowCheetah 和FastKoala 似乎是非常好的工具,可以帮助解决这个问题。

However, if you want to avoid addins or use the principles they implement more extensively throughout your build/integration processes then adding this to your msbuild *proj files is a shorthand fix.

但是,如果您想避免插件或使用它们在整个构建/集成过程中更广泛地实现的原则,那么将其添加到您的 msbuild *proj 文件是一种速记修复。

Note: this is more or less a rework of the No. 2 of @oleksii's answer.

注意:这或多或少是@oleksii 答案的第 2 项的返工。

This works for .exe and .dll projects:

这适用于 .exe 和 .dll 项目:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
  </Target>

This works for web projects:

这适用于网络项目:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
  </Target>

Note that this step happens even before the build proper begins. The transformation of the config file happens in the project folder. So that the transformed web.config is available when you are debugging (a drawback of SlowCheetah).

请注意,此步骤甚至在构建正确开始之前就发生了。配置文件的转换发生在项目文件夹中。以便在调试时可以使用转换后的 web.config(SlowCheetah 的一个缺点)。

Do remember that if you create the App_Config folder (or whatever you choose to call it), the various intermediate config files should have a Build Action = None, and Copy to Output Directory = Do not copy.

请记住,如果您创建 App_Config 文件夹(或您选择的任何名称),则各种中间配置文件应具有 Build Action = None 和 Copy to Output Directory = Do not copy。

This combines both options into one block. The appropriate one is executed based on conditions. The TransformXml task is defined first though:

这将两个选项合并为一个块。根据条件执行适当的一个。虽然首先定义了 TransformXml 任务:

<Project>
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Condition="Exists('App_Config\app.Base.config')" Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
    <TransformXml Condition="Exists('App_Config\Web.Base.config')" Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
</Target>

回答by TGasdf

See if the XDT (web.config) transform engine can help you. Currently it's only natively supported for web projects, but technically there is nothing stopping you from using it in other application types. There are many guides on how to use XDT by manually editing the project files, but I found a plugin that works great: https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

看看 XDT (web.config) 转换引擎是否可以帮助您。目前,它仅对 Web 项目提供本机支持,但从技术上讲,没有什么能阻止您在其他应用程序类型中使用它。有很多关于如何通过手动编辑项目文件来使用 XDT 的指南,但我发现了一个很好用的插件:https: //visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

The plugin is only helping to setup the configuration, it's not needed to build and the solution can be built on other machines or on a build server without the plugin or any other tools being required.

该插件仅帮助设置配置,不需要构建,解决方案可以在其他机器或构建服务器上构建,无需插件或任何其他工具。

回答by Janbro

I have solved this topic with the solution I have found here: http://www.blackwasp.co.uk/SwitchConfig.aspx

我已经用我在这里找到的解决方案解决了这个话题:http: //www.blackwasp.co.uk/SwitchConfig.aspx

In short what they state there is: "by adding a post-build event.[...] We need to add the following:

简而言之,他们声明的是:“通过添加构建后事件。[...] 我们需要添加以下内容:

if "Debug"=="$(ConfigurationName)" goto :nocopy
del "$(TargetPath).config"
copy "$(ProjectDir)\Release.config" "$(TargetPath).config"
:nocopy

回答by Mike

I have heard good things about SlowCheetah, but was unable to get it to work. I did the following: add am tag to each for a specific configuration.

我听说过关于 SlowCheetah 的好消息,但无法让它发挥作用。我执行了以下操作:为每个特定配置添加 am 标记。

Ex:

前任:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'UAT|AnyCPU'">
    <OutputPath>bin\UAT\</OutputPath>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <AppConfig>App.UAT.config</AppConfig>
  </PropertyGroup>

回答by Mark Redman

After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

在对开发和构建等管理配置进行了一些研究之后,我决定自己动手,我已经在 bitbucket 上提供了它:https://bitbucket.org/brightertools/contemplate/wiki/Home

This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

这是用于多个环境的多个配置文件,它是一个基本的配置条目替换工具,可以处理任何基于文本的文件格式。

Hope this helps.

希望这可以帮助。