visual-studiomsbuildcsprojdocfx

PackageReference condition is ignored


In my VS 2017 project I reference docfx.console package and I want it to be used only when certain condition is met. But the package gets used for all builds.

Here is a part of my project. I want docfx.console to be used when configuration is Installer/AnyCPU and VS is building net40 flavor.

<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net40;netstandard1.3;netstandard2.0</TargetFrameworks>
    <!-- ... -->
    <Configurations>Debug;Release;Installer</Configurations>
  </PropertyGroup>

  <ItemGroup Condition=" '$(TargetFramework)'=='net40' ">
    <!-- ... -->
    <PackageReference Include="docfx.console" Version="2.30.0" Condition="'$(Configuration)|$(Platform)'=='Installer|AnyCPU'" />
  </ItemGroup>

    <!-- ... -->
</Project>

Is there a way to use docfx.console in Installer build for net40 only?


Solution

  • Even i was looking for referencing nuget packages on condition based (load only when expected constant is set in DefineConstants). Though @Luke Schoen Solution worked for me, I could make it work without the external targets file.

    Solution is to include your PackageReference using Choose > When

    Make sure to have this block after your PropertyGroup which has DefineConstants.

    <Choose>
        <When Condition="$(DefineConstants.Contains('My_CONST'))">
            <ItemGroup>
                <PackageReference Include="MyPackage">
                    <Version>1.0.6</Version>
                </PackageReference>
            </ItemGroup>
        </When>
    </Choose>