-->

How to restrict a NuGet package from upgrading beyond a version

dev nuget, dotnet

Package management is quite easy with .NET as we have NuGet as the default package manager. We have direct access to hundreds of thousands of packages freely hosted at NuGet.org.

Recently, a free package called FluentAssetions, which is a very popular NuGet package, became a paid product. So if you upgrade from the free version 7 to paid version 8 you have to pay for the package.

Normally when you start using a package it’s easy to upgrade. NuGet automatically upgrades everything to the latest version. This made me think, if you are using FluentAssertions, it may cause some issues if you have developers who aren’t aware of the licensing issue. They may without realizing license difference, automatically upgrade to a paid version.

To avoid this issue, you can control the version of your packages. Let’s see how it works in a demo application. Open a terminal and choose a directory that you want to work in.

Then run the following commands:

mkdir NuGetVersioningDemo
cd NuGetVersioningDemo
dotnet new console

Now you should have a new Console Application created in your directory. Open it with your IDE.

Add Newtonsoft.Json package to work with package versions by running the following command:

dotnet add package Newtonsoft.Json

At this point, your project should look like this (I’m using JetBrains Rider in this example but it the project structure and the NuGet package should look similar if you’re using a different IDE):

Screenshot of the project setup with a NuGet package added

If you don’t specify the version, NuGet automatically fetches the latest version which in this case is 13.0.3. To get a specific version you can use the same dotnet command and provide the version as shown in the example below:

dotnet add package Newtonsoft.Json --version 12.0.1

So for the sake of demonstrating version control, let’s assume Newtonsoft.Json became a paid product as of version 13 and you want to upgrade to all versions up to v13. I didn’t use actual FluentAssertions in this example because I didn’t want anyone to make a mistake and accidentally upgrade to the paid version.

The way to manage the versions is using square brackets and parentheses.

For example, the following command installs the latest package up until v13

dotnet add package Newtonsoft.Json --version "[*,13)"

This way you can lock in the maximum version you want to install for a specific version.

Resources