Conditional reference in Visual Studio Community 2017
Asked Answered
I

2

16

I am creating a multi-platform application. I have a multi-targeted shared library (targeting .netstandard 2.0 and .net 4.5)...See project file:

  <PropertyGroup>
    <TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
  </PropertyGroup>

When I build the project in visual studio 2017 on windows, I get two directories in the output (netstandard2.0, net45) and the corresponding dlls. The build is a success.

When I build the exact same project (same code) in visual studio 2017 on a mac, I get errors of this nature:

The type 'OptionAttribute' exists in both 'CommandLine.DotNetStandard, Version=1.0.30' and 'CommandLine, Version=1.9.71.2'

I conditionally referenced a command line parser library in the following way:

  <!-- CommandLineParser library -->
  <ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
    <PackageReference Include="CommandLine.DotNetStandard">
      <Version>1.0.3</Version>
    </PackageReference>
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net45'">
    <PackageReference Include="CommandLineParser">
      <Version>1.9.71</Version>
    </PackageReference>
  </ItemGroup>

This works great for windows, but on the mac it appears it is not observing the condition. Is this a known bug for visual studio on mac? Am I doing something wrong?

Instinct answered 17/10, 2017 at 17:42 Comment(1)
Possible duplicate of PackageReference condition is ignoredHofstetter
V
22

Visual Studio ignores the condition in these cases. Use a Choose/When instead, that should be fully supported: https://msdn.microsoft.com/en-us/library/ms164282.aspx

<Choose> 
  <When Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
    <ItemGroup>
      <PackageReference Include="CommandLine.DotNetStandard">
        <Version>1.0.3</Version>
      </PackageReference>
    </ItemGroup>
  </When>
  <When Condition=" '$(TargetFramework)' == 'net45' ">
    <ItemGroup> 
      <PackageReference Include="CommandLineParser">
        <Version>1.9.71</Version>
      </PackageReference>
    </ItemGroup>
  </When>
</Choose>
Viviparous answered 17/10, 2017 at 18:16 Comment(2)
yeah, but too bad that msbuild simply silently ignores the conditions, thus masking the real problem.Viviennevivify
This didn't solve the problem for me since it keeps ignoring the condition of the seconds target.Varve
B
2

If MsBuild is taking into account only your first <Choose/> or condition then you'd want to do this:

 <Choose>
    <When Condition="'$(Configuration)'=='Debug'">
      <ItemGroup>
        <ProjectReference Include="..\path\to_your_project.csproj" />
      </ItemGroup>
    </When>
    <Otherwise>
      <ItemGroup>
        <PackageReference Include="Package-Name" Version="1.0.0"/>
      </ItemGroup>
    </Otherwise>
  </Choose>
Babar answered 23/10, 2019 at 1:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.