Creating NuGet package for multiple .NET Framework versions

Viewed 3504

I'm developing a library and want to create NuGet package for multiple versions of .NET Framework. I didn't find any article with full list of actions to do this.

The first option I've tried was creation of bunch of configurations like Release_Net45 and so on. I then edited csproj to correct output directories (lib/net45 and so on) and target framework versions for each configuration. Then I built each configuration. After that I ran nuget pack and package was succesfully created with one warning that one dll was not added since it is already in the package...

Then I've tried to edit csproj to include TargetFrameworks element and elements for package metadata to the PropertyGroup corresponding to the Release configuration. After reloading the project after editing, new group called Dependencies was appeared in the Solution Explorer. I made a try to create package with msbuild /t:pack /p:Configuration=Release in Developer Command Prompt but it was finished with error that there is no pack target. To fix it I added NuGet.Build.Tasks.Pack package and after that the package was built. BUT my configurations suddenly became corrupted when I looking at them in Configuration Manager.

I didn't expect that setting up a package for multiple target frameworks will be such painful :( What is the correct way to do this? Is there any complete guide for this task?

1 Answers

The TargetFramework / TargetFrameworks properties are only supported in SDK-based projects. Currently, only the project templates for .NET Standard, .NET Core and ASP.NET Core projects use this SDK-based project format. So you can create a .NET Standard library and then edit the csproj (right click on the project > edit).

A minimal example would be:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net45;net461</TargetFrameworks>
  </PropertyGroup>
</Project>

Notice the presence of the Sdk attribute which provides a lot of defaults and additional build logic. You do not need to specify any .cs files in the folder structures and can use the project's property pages to set NuGet-related properties.

The reason the dependencies node was shown in your case is because VS 2017 ships with two distinct project systems for .NET projects - the classic one that has been in VS for a long time and a new one being developed on a new project system model (CPS) which doesn't support all the features of the classic project system yet but has additional ones like a new dependencies model, property pages for NuGet and support for editing project files while projects are loaded. The selection which project system to load is based on the presence of either TargetFramework or TargetFrameworks in the project file.

Related