...

/

Packaging Libraries for NuGet Distribution

Packaging Libraries for NuGet Distribution

Learn about referencing NuGet packages, fixing dependencies, and packaging a library for distribution on NuGet.

Before we learn how to create and package our own libraries, we will review how a project can use an existing package.

Referencing a NuGet package

Let’s say that we want to add a package created by a third-party developer, for example, Newtonsoft.Json, a popular package for working with the JavaScript Object Notation (JSON) serialization format:

Step 1: In the AssembliesAndNamespaces project, add a reference to the Newtonsoft.Json NuGet package, either using the GUI for Visual Studio 2022 or the dotnet add package command for Visual Studio Code.

Step 2: Open the AssembliesAndNamespaces.csproj file and note that a package reference has been added, as shown in the following markup:

Press + to interact
<ItemGroup>
<PackageReference Include="newtonsoft.json" Version="13.0.1" />
</ItemGroup>

Fixing dependencies

To consistently restore packages and write reliable code, it’s important that we fix dependencies. Fixing dependencies means we are using the same family of packages released for a specific version of .NET, for example, SQLite for .NET 7.0, as shown highlighted in the following markup:

Press + to interact
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference
Include="Microsoft.EntityFrameworkCore.Sqlite"
Version="7.0.0" />
</ItemGroup>
</Project>

To fix dependencies, every package should have a single version with no additional qualifiers. Additional qualifiers include betas (beta1), release candidates (rc4), and wildcards (*). ...