Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There a Way to Force a Project Reference to .NET Standard Project to a Specific TargetFramework

I am a contributor to a GitHub project, and recently we had some trouble with our .NET Standard 2.0 project installing correctly into a .NET Framework 4.5 project. The cause of this is that (if I am understanding correctly) .NET Standard 2.0 supports a minimum .NET Framework of 4.6.1.

OK, fair enough. So we updated the .csproj to create another framework output:

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

In our testing project, the supported frameworks are defined as such:

<TargetFrameworks>netcoreapp2.0;net471;net45</TargetFrameworks>

However, we are running into a problem with the net471 build as it seems to be picking up the net45 framework and not the netstandard2.0. In order to get this working, we are having to set the TargetFrameworks of the class library as such:

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

This seems excessive as it would seem that .netstandard2.0 should be the TargetFramework that net471 picks up, rather than the net45 target.

Is there a way to force a project reference to a particular TargetFramework? I did try the following in our testing project, but it did not seem work:

<ItemGroup Condition="'$(TargetFramework)' != 'net471'">
  <ProjectReference Include="..\..\src\ExtendedXmlSerializer\ExtendedXmlSerializer.csproj" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net471'">
  <ProjectReference Include="..\..\src\ExtendedXmlSerializer\ExtendedXmlSerializer.csproj">
    <TargetFramework>netstandard2.0</TargetFramework>
  </ProjectReference>
</ItemGroup>

Thank you in advance for any assistance you can provide!

like image 329
Mike-E Avatar asked Jan 30 '18 16:01

Mike-E


2 Answers

Update 2020: The answer suggesting to use SetTargetFramework is a better fit, also to not conflict with other settings.

You can change your project reference like this:

  <ProjectReference Include="..\..\src\ExtendedXmlSerializer\ExtendedXmlSerializer.csproj" 
                    AdditionalProperties="TargetFramework=netstandard2.0" />

to force the selection of a specific target framework over the default "get nearest TFM" logic.

like image 171
Martin Ullrich Avatar answered Sep 18 '22 18:09

Martin Ullrich


It does not work. VS 2017 15.5.5. Reference from 4.6.2 MSTest project net462 target of multitarget (net462;netstandard2.0) class library. – SerG Feb 13 at 13:34

It is true, the new way to solve that is this:

<ProjectReference Include="..\multitargeted_lib\multitargeted_lib.csproj">
  <SetTargetFramework>TargetFramework=netstandard2.0</SetTargetFramework>
</ProjectReference>

Source is here.

like image 20
Lorenzo Isidori Avatar answered Sep 19 '22 18:09

Lorenzo Isidori