Setting a different App.config for every publish environment (Config Transformation)

Unlike the Web.config is not possible to setup a config transformation for the App.config in a non Web project.
Here is how to manually setup this behavior in VS.

First of all we manually create an App.config for every build configuration (the “Add Config Transform” option is not available for App.config), So we create an App.Debug.config and an App.Release.config in this way:

We can see that the App.config are not grouped together as they are when using the “Add Config Transform” option with the Web.config. This because no relation is set between the files at project level. To add this we need to open the .csproj file and to search for “app.config”. We’ll find something similar to this:

<ItemGroup>  <None Include="App.config" />
  <None Include="App.Release.config" />
  <None Include="App.Debug.config" />
  <None Include="packages.config" />

To specify the relation we need to update it in this way:

  <Content Include="App.config" />
  <Content Include="App.Release.config">
  <Content Include="App.Debug.config">
  <None Include="packages.config" />

And here is the final effect:

Now that we have our config transformation files in place we just need to tell VS to use them, based on the build configuration we are using. To do this we need to edit the .csproj file again and to add this part at the end of the file, just before the last closing tag.

<UsingTask TaskName="TransformXml"
           AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
  <!-- Generate transformed app config in the intermediate directory -->
  <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config"
                Transform="app.$(Configuration).config" />
  <!-- Force build process to use the transformed configuration file from now on. -->
    <AppConfigWithTargetPath Remove="app.config" />
    <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">

After this we’ll be able to have a different App.config generated from our config transformations, based on the current build configuration.

Here is how an empty config transformation file looks like:

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s