NuGet is a package manager for the Microsoft development environment. Nowadays the requirements for the applications are more complex than ever. It’s very hard for a development team to implement all the code used in a complex system, especially the generic utilities which are common for all applications and not specific to the application domain. This is where consuming already developed packages comes in very helpful.

What’s a NuGet package?

A Nuget package is a zip file, with .nupkg extension, that contains compiled code, other related files and some descriptive metadata. This metadata contains the package version, author info and some other optional information. You’ll learn more about it later in this article.

Why use the NuGet package manager?

As stated before, it’s next to impossible to develop a mid to large-sized application without using any external packages. To manage the packages you consume, you will need a package manager.

The benefits of using NuGet package manager can be summarized as below:

Easy Package Management

NuGet simplifies the process of managing third-party libraries and tools in your projects. It provides a centralized repository where you can discover, download, and install packages with just a few clicks.

Dependency Management

NuGet automatically manages dependencies between packages. When you install a package, NuGet ensures that any other packages it depends on are also installed. This helps prevent version conflicts and ensures that your project uses compatible versions of libraries.

Versioning

NuGet packages are versioned, allowing you to specify the exact version of a package that your project needs. This helps maintain consistency across development, testing, and production environments.

Integration with Visual Studio and other popular IDEs

NuGet is tightly integrated with Visual Studio, which is the primary integrated development environment (IDE) for .NET development. This integration makes it easy to manage packages directly from the Visual Studio IDE.

Command-Line Interface (CLI)

In addition to the Visual Studio integration, NuGet provides a command-line interface (CLI) for those who prefer working in a console environment. This flexibility allows developers to incorporate package management into their build scripts and automation processes.

Community Contributions

NuGet has a large and active community of developers who contribute packages to the NuGet Gallery. This means you can easily access a wide range of libraries and tools created by others, saving you from reinventing the wheel.

NuGet Gallery

The NuGet Gallery serves as a central repository for NuGet packages, making it a convenient hub for sharing and discovering packages. You can find packages for various purposes and from different authors in one place.

Package Restoration

NuGet simplifies the process of restoring packages in a project. When you open a project on a new machine or a different environment, NuGet can automatically download and install the required packages, reducing setup time.

NuGet.org

NuGet.org, the official NuGet package source, is a reliable and well-maintained repository. It ensures that the packages you download are trustworthy and have passed certain quality standards.

How to install NuGet?

There are a number of ways to use NuGet. For legacy projects (.NET Framework projects) you can download Nuget CLI directly. For more info, check out how to Install NuGet Client tools.

dotnet CLI used to have its own repository, but nowadays, it’s part of the .NET SDK. You can download the dotnet framework here as well.

If you already have Visual Studio or JetBrains Rider installed on your system you should have the required CLIs installed already. This article will use the dotnet CLI and dotnet 7 in the demo project.

To test your CLI installation, run the following command:

dotnet --version

You should see the dotnet version printed on your terminal window.

Demo Project Setup

To follow along and practice using NuGet, it’s advised you follow the steps below to create your own playground. Alternatively, you can clone the accompanying GitHub repository to get the final code:

git clone https://github.com/cloudinternals/public-source-code --branch blog/nuget-basics

Run the following snippet to create the project:

mkdir NuGetBasics
cd NuGetBasics
dotnet new console

NuGet Package Metadata

The metadata in a NuGet package is stored in an XML file with .nuspec extension. The mandatory elements are:

<id></id>
<version></version>
<description></description>
<authors></authors>

You can also also projectUrl, license, icon etc. you can find the full list of elements here.

To see the .nuspec file in action, run the following command in your terminal while in the same directory as the .csproj file:

dotnet pack

You should see an output like this:

The output of dotnet pack command

Then run the following command to check the contents of the bin/Debug folder:

ls -la ./bin/Debug
Terminal window showing the contents of bin/Debug directory

As stated before, .nupkg is simply a zip file. You can change the extension and unpack by running the following commands:

mv ./bin/Debug/NuGetBasics.1.0.0.nupkg NuGetBasics.zip
unzip NuGetBasics.zip -d package-contents
ls -la ./package-contents

You should see an output like this:

Terminal window showing the commands to rename the .nupkg file to a zip file, extract it and list the contents

You can see the NugetBasics.nuspec file listed in the directory.

Open the file in a text editor and it should look like this:

Contents of .nuspec file showing the required elements

When you run the dotnet pack command, it automatically populates the required XML elements with default values.

Instead of packaging your output with an extra command like this, you can specify to create a package with every build. To achieve this, edit your .csproj file and add the following line in the PropertyGroup element:

<GeneratePackageOnBuild>true</GeneratePackageOnBuild>

How to consume NuGet packages

In the demo project, you want to get the path of a JSON file, read it, parse it and display it in the console window. To achieve this, update Program.cs with the following code:

var filepath = args[0];

using (StreamReader file = File.OpenText(filepath))
using (JsonTextReader reader = new JsonTextReader(file))
{
    JObject obj = (JObject)JToken.ReadFrom(reader);
    Console.WriteLine(obj);
}

This is just a sample code taken from the Newtonsoft.Json package’s website. It’s probably one of the most popular Nuget packages that has been used in lots of different projects. Instead of reinventing the wheel, you would naturally want to leverage using this library and quickly implement your own solution. To be able to use this library, first, you need to add it to your project by running the following command:

dotnet add package Newtonsoft.Json

Next, add the references to the library on top of the Program.cs file as shown below:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Now, you can run your application by providing a path to a JSON file (you can find a sample in the GitHub repo at this path)

The output should look like this:

Terminal window showing the output of a sample JSON file

By running a single command you now have all this JSON parsing functionality available to you in your application for free.

If you open the .csproj file, you should see the reference to the package:

The version number in your project may differ based on when you are downloading the package.

To update the package, all you have to to is run the same command (dotnet add package). If the package already exists and there is a newer version, it automatically downloads the latest and updates the reference in the project file.

If you want to remove a reference to a package, you can run the following command:

dotnet remove package Newtonsoft.Json

Conclusion

In this article, you looked into the main benefits of package management and the basics of NuGet packages. You also covered how to use packages using a demo application. There is a lot more involved with packages such as creating and publishing your own packages, hosting your own private repositories etc. which will be covered in future articles.

Resources