I recently ran into a situation where I needed to have a single project in Visual Studio build the application two different ways with each way using different DLL references. The normal Project Properties provide all sorts of mechanisms for build-specific options but Microsoft seems to have left the ability to specify conditional library references out of it for some reason.
It turns out that while they did leave it out of Visual Studio, it is available in MSBuild which Visual Studio uses to actually compile the code.
Here is how it works:
- Open your solution in Visual Studio
- Select Build – Configuration Manager and select <New…> from the drop down in the top left corner.
- Create the new config based on whatever current profile makes sense
- Hit OK to create your alternative configuration
- Right-click on your project file in Visual Studio and select ‘Open folder in Windows Explorer’
- Close Visual Studio
- Use your favorite text editor to edit the Visual Studio Project file (*.csproj or *.vbproj)
- Locate the library reference that you want to make conditional within the <ItemGroup> element
- Duplicate the entire <Reference… > nodes that you want to vary by build
- For each reference, add a new ‘Condition=…’ attribute as shown in the block below
<ItemGroup> <Reference Include="Microsoft.SharePoint, Version=220.127.116.11, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL" Condition="'$(Configuration)'=='Debug2007'"> <SpecificVersion>False</SpecificVersion> <HintPath>..\DLLReferences\2007\Microsoft.SharePoint.dll</HintPath> </Reference> <Reference Include="Microsoft.SharePoint, Version=18.104.22.168, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL" Condition="'$(Configuration)'=='Debug2010'"> <SpecificVersion>False</SpecificVersion> <HintPath>..\DLLReferences\2010\Microsoft.SharePoint.dll</HintPath> <Private>True</Private> </Reference> </ItemGroup>
- The basic syntax looks clumsy but is actually pretty straightforward: Condition=”‘$(Configuration)’==’YourBuildName1′”. You will need to specify this for each of your builds
- Save the file and reopen the solution in Visual Studio. You should now be able to simply change your build configuration from the toolbar and build using each set of DLLs
The Visual Studio UI doesn’t always keep up with the conditional references and you may see what appears to be the ‘broken reference’ icon next to your references in the tree. This is nothing to worry about though as everything will still build fine and the UI does catch up eventually.
Also, you may want to change the Output Path (Project Properties – Build) to different folders for each of the build configurations in order to prevent them from stepping on each other.
Naturally, once I had a working solution and knew exactly what to look for I was able to track down the actual documentation from Microsoft, kinda. This approach also supports Platform-specific conditions as well.