Enabling NuGet central package management

August 16th 2024 NuGet .NET

When you have many projects in your Visual Studio solution, it's not uncommon that the same NuGet packages are installed in multiple projects. In such a case, it's all too easy for the version of the same NuGet package in different projects to diverge. Once you notice this problem, you can quickly fix it with the Consolidate tab of the NuGet Package Manager in Visual Studio. But it would be even better if you could prevent it from happening in the first place.

Central package management promises to achieve exactly that:

  • You can keep the version of every package used by one or more projects in the common Directory.Packages.Props file in the solution/repository root folder.
  • You can (and must) remove the version information for the packages from the project files, as the version from the above mentioned file will be used.

Once you set it up, all common .NET IDEs (Visual Studio 2022, Visual Studio Code with C# Dev Kit and Rider) recognize it and change the way they handle NuGet package management: they correctly maintain the common package versions for all projects in the Directory.Packages.Props file and keep the list of installed packages in the project files without version information.

The biggest issue with central package management is setting it up for an already large solution with many projects and installed packages. There's no support for it in any of the IDEs and the official documentation describes the process of manually creating the Directory.Packages.Props file and modifying all the project files.

Fortunately, there's a global tool available which can do exactly this for you: CpmMigrator. You first need to install it globally:

dotnet tool install -g CentralPackageManagementMigrator.Runner

Then you can move to the root folder of your solution and invoke the command with the name of your solution file:

CpmMigrator -s .\WebApiTesting.sln

Although The tool was still at version 0.2.2 at the time of writing and hasn't been updated for almost two years, it worked perfectly for the couple of solutions I tried it with. Definitely a faster and less error-prone alternative to the manual process.

You can check the latest commit in my GitHub repository to see what it did to a pretty simple sample solution. But it's probably better to try it out on your own less trivial solution.

Central package management makes it much easier to consistently use the same version of a NuGet package across all projects in a solution. Converting a large solution with many projects and package references to central package management following the documented manual process can be time consuming and error prone. However, the CpmMigrator global tool can do it for you.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License