.net.net-coremsbuildtarget-framework

"dotnet build" on project targeting multiple frameworks is only building "netstandard2.0" and not generating nupkg file


I have a project that is targeting both net472 and netstandard2.0. When I build the project in VisualStudio, both frameworks are generated in the output directory and a .nupkg file is generated, as expected.

When trying to build the same project in the CLI with dotnet build it only builds the netstandard2.0 project and not the net472. Also, the .nupkg isn't generated (presumably because all targets aren't available, but I'm not sure).

I have other projects that are setup the same way as this project but only target netstandard2.0 and these projects generate the .nupkg when using dotnet build.

How do I get dotnet to build the project with both frameworks and generate the .nupkg file? From my understanding, dotnet build is supposed to build all targeted frameworks unless the -f switch is provided.

Here's a slightly modified version of the project file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net472;netstandard2.0</TargetFrameworks>
  </PropertyGroup>

  <!-- .NET 4.7.2 only packages -->
  <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
    <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.7" />
  </ItemGroup>

  <!-- All framework packages -->
  <ItemGroup>
    <PackageReference Include="System.Net.Http" Version="4.3.4" />
  </ItemGroup>

  <!-- Project references -->
  <ItemGroup>
    <!-- Various reference in here -->
  </ItemGroup>

</Project>

Additional info:

dotnet --version: 3.1.300

msbuild -version: 16.5.0.12403


Solution

  • While looking for other build configurations that may causing this, I opened Directory.Build.props in my solution folder and noticed the following:

    <!-- SDK Default Framework -->
    <PropertyGroup>
      <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>
    

    Because both TargetFramework and TargetFrameworks elements were both present in the final config, dotnet build must have been using the TargetFramework value and ignoring TargetFrameworks.

    My solution was to remove the element from Directory.Build.props and add the element to each .csproj in the solution.

    There is probably also a solution that would allow you to remove the TargetFramework element from the project that also uses TargetFrameworks, but I didn't spent much time looking for one.