Wednesday, March 13, 2013

Conditionally referencing DEBUG and RELEASE builds in Visual Studio projects

This is a little neat trick I learned from someone on stackexchange.com.  When adding a reference to an assembly in Visual Studio projects one can choose only one type of the assembly build DEBUG or RELEASE. There is no way in the IDE to reference DEBUG assembly when making DEBUG builds of your projects and reference RELEASE assembly when making RELEASE builds.  But this can be achieved by directly editing the project file (extension .csproj for a C# project, for example) in any text editor. A typical hint path entry for the referenced assembly looks like this

    <Reference Include="ReferenceAssembly, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\externals\Release\ReferenceAssembly.dll</HintPath>
</Reference>



The project file is in MSBUILD format and that allows us to use built-in project property $(Configuration) to conditionally point to different locations of the same assembly depending on the current build configuration of DEBUG or RELEASE

    <Reference Include="ReferenceAssembly, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\externals\$(Configuration)\ReferenceAssembly.dll</HintPath>
</Reference>



In this case, when making a DEBUG build of project the ReferenceAssembly.dll from ..\..\..\externals\Debug\ folder will be referenced. And when making RELEASE build the assembly will be picked up from ..\..\..\externals\Release\ folder.




In fact, we can also choose to reference assemblies in different paths like this

<Reference Include="ReferenceAssembly, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">   
<HintPath Condition="'$(Configuration)' == 'Debug'">..\..\..\path1\ReferenceAssembly.dll</HintPath>
<HintPath Condition="'$(Configuration)' == 'Release'">..\..\..\path2\ReferenceAssembly.dll</HintPath>
</Reference>



4 comments:

  1. Awesome! Thank you! We need to prod VStudio team to include this as an option in the IDE.

    ReplyDelete
  2. This solution eliminates the "broken reference" that the Visual Studio GUI displays when a condition evaluates to false. The key is that the condition is placed on the HintPath, and not on the Reference node.

    ReplyDelete
  3. Thanks, this is a great solution to troubleshoot. When I was looking for a similar solution, I found msvcr120.dll missing https://fix4dll.com/msvcr120_dll , this application helped me fix my problem. So your post is very useful too. I will definitely try next time to fix my problem with the help of your option.

    ReplyDelete