Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify targetFramework for PackageReference in .csproj file?

I have a problem starting with VS2017 and the new PackageReference for NuGet dependencies.

At first I was excited that this extra packages.config file is not needed anymore. But now I am a bit disappointed:

Some of my assemblies target framework 4.0 because they must be able to run under XP also. Others do not have this limitation and target framework 4.6.1. This works fine because no 4.0 assembly have a dependency on a 4.6.1 assembly. Only the other direction.

Most assemblies uses the NLog NuGet package. But when using the new PackageReference option for specifying the NuGet packages, the assemblies targeting framework 4.6.1 will always install the NLog variant targeting .NET 4.5. From then on, other assemblies depending on a .NET 4.0 assembly cannot be build anymore:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(1987,5): warning MSB3275: The primary reference "Tools, Version=2.0.0.9180, Culture=neutral, processorArchitecture=MSIL" could not be resolved because it has an indirect dependency on the assembly "NLog, Version=3.2.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c" which was built against the ".NETFramework,Version=v4.5" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.0". [D:\Work\4.8.0_PackageReference\Test\TestApp.csproj]

I want to use NLog for .NET 4.0 for all projects. Is this really not possible without packages.config? There one could specify the desired framework with the targetFramework attribute. But I could not find any way to do this with the new PackageReference approach. That is unbelievable...

like image 887
user2452157 Avatar asked Sep 28 '17 14:09

user2452157


People also ask

What is package config TargetFramework?

packages. config: The targetframework attribute of a dependency specifies the variant of a package to install.

How do I target multiple net frameworks?

To target multiple frameworks, change <TargetFramework> to plural <TargetFrameworks> and include monikers for different frameworks you want to target separated by ; . Here, we will support two more frameworks . NET Framework 4.0 & 4.6. So include net40 and net46 monikers respectively as shown below.


1 Answers

<ItemGroup>
    <!-- ... -->
    <PackageReference Include="Newtonsoft.Json" Version="9.0.1" Condition="'$(TargetFramework)' == 'net452'" />
    <!-- ... -->
</ItemGroup>

MS doc link: https://docs.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#adding-a-packagereference-condition

like image 58
ryancheung Avatar answered Sep 18 '22 10:09

ryancheung