Packages, NuGet packages and Custom NuGet Packages in ASP.NET Core

AZHARUL | 15-Oct-2024 09:48:36 AM | Time to read: 7 Min

In modern software development, one of the key practices is reusing existing code or libraries to accelerate development and reduce errors. Packages and NuGet packages in ASP.NET Core are essential tools that allow developers to reuse code efficiently across different projects and teams. In this blog, we will explore:

  • What packages and NuGet packages are.
  • How to create a custom NuGet package using Visual Studio.
  • How to add the custom package to a new project and implement it in real-world scenarios.

In this blog  we'll use real-life software development examples to make it easy for readers to follow along.

What Are Packages and NuGet Packages in ASP.NET Core?

A package in ASP.NET Core is a reusable piece of code or functionality that can be shared across projects. Most of the time, packages are distributed via NuGet, which is the official package manager for ASP.NET. These packages can be third-party libraries (such as Newtonsoft.Json for JSON handling), development tools, or even custom packages created within your own organization.

A NuGet package is a zip file with a .nupkg extension, containing precompiled code, resources, and metadata about the package. The primary benefits of using packages are:

  1. Reusability: Write code once and use it across multiple projects.
  2. Dependency Management: Automatically include and manage dependencies of your libraries.
  3. Versioning: Use version control to ensure compatibility between different versions of packages.

Scenario: Creating a Custom Package in a Real-World Development Project

Let’s say you are working on multiple software projects where you need to handle logging, error handling, or common utilities like math operations, and you want to share the code among all projects. Instead of duplicating the code, you can create a custom NuGet package for these utility functions.

In this section, we will create a custom NuGet package using Visual Studio and demonstrate how to use it in a different project.

 

Step-by-Step: How to Create a Custom NuGet Package in Visual Studio

 

Step 1: Set Up a Class Library

  1. Open Visual Studio and go to File → New → Project.
  2. Select Class Library (.NET Core) and name it CodexoomCompany.Utilities.
  3. Choose the target framework (e.g., .NET 6).

Now, we have a basic class library project set up where we will add some reusable functionality.

Step 2: Add Utility Code to the Class Library

Let’s create a logging utility class that other projects can use to write logs to a file.

  1. In the CodexoomCompany.Utilities project, right-click the project and select Add → Class.
  2. Name the class Logger.cs and implement basic logging functionality like this:
using System;
using System.IO;
namespace CodexoomCompany.Utilities
{
    public static class Logger
    {
        private static string logFilePath = "log.txt";
        public static void Log(string message)
        {
            using (StreamWriter writer = new StreamWriter(logFilePath, true))
            {
                writer.WriteLine($"{DateTime.Now}: {message}");
            }
        }
    }
}

This simple Logger class writes logs to a text file (log.txt). Now, instead of duplicating this logic in different projects, we can package it and reuse it.

Step 3: Configure Package Metadata

  1. Right-click on the CodexoomCompany.Utilities project in Solution Explorer and select Properties.
  2. Navigate to the Package tab and fill in the metadata fields such as:
    • Package ID: CodexoomCompany.Utilities
    • Version: 1.0.0
    • Description: Logging utility for file-based logging.
    • Authors: Your name or organization.
  3. Save the project settings.

Step 4: Build the NuGet Package

  1. Right-click the project in Solution Explorer and select Pack.
  2. This action will generate a NuGet package (.nupkg file) in the bin\Debug folder of your project.

Congratulations! You’ve just created your first custom NuGet package that can be used in any project within your organization or even distributed to other teams.

 

Using the Custom Package in a New Project

 

Now that we have a reusable NuGet package, let’s add it to a new project and see how it can be used in a real-world scenario.

Step 1: Create a New .NET Core Console Application

  1. In Visual Studio, go to File → New → Project.
  2. Select Console App (.NET Core) and name it CodexoomCompany.Application.
  3. Choose the same framework as your library (e.g., .NET 6).

Step 2: Add the Custom Package to the Console Application

  1. Right-click the CodexoomCompany.Application project and select Manage NuGet Packages.
  2. Click on the gear icon in the top-right corner of the NuGet Package Manager window and select Add Package Source.
  3. Set the Source to the folder where your .nupkg file is located (usually bin\Debug\ of your class library).
  4. After adding the source, search for CodexoomCompany.Utilities in the Browse tab and click Install.

Step 3: Use the Custom Package in the Console Application

Now that the CodexoomCompany.Utilities package is added to the project, we can use the Logger class to implement file-based logging.

Open Program.cs and add the following code:

using CodexoomCompany.Utilities;
class Program
{
    static void Main(string[] args)
    {
        Logger.Log("Application started.");
        Console.WriteLine("Welcome to CodexoomCompany's Application!");
        Logger.Log("Application is processing data...");
        Console.WriteLine("Processing data...");
        Logger.Log("Application finished successfully.");
        Console.WriteLine("Finished.");
    }
}

Run the application. The log entries will be written to log.txt, and the console will display messages. This is a simple yet practical example of how you can reuse a custom package in multiple projects.

Additional Benefits of Creating Custom Packages

In real-life software development, you may create multiple custom packages to encapsulate specific functionality. Here are some examples where creating packages can streamline your development workflow:

  1. Authentication and Authorization Libraries: Create a custom package for handling authentication logic that can be reused across different web applications.
  2. Database Access Libraries: Use a common data access layer, encapsulated in a package, to ensure uniform database handling across your projects.
  3. Custom UI Components: For front-end developers working with Blazor or ASP.NET MVC, reusable components like buttons, modals, or tables can be distributed as packages.

These custom packages reduce duplication of code, improve consistency, and help manage updates across multiple projects.

In this blog, we explored:

  • What packages and NuGet packages are in .NET Core.
  • How to create a custom NuGet package using Visual Studio with a real-life example.
  • How to add and implement the custom package in another project.

Creating and using custom NuGet packages helps developers share code, manage dependencies, and ensure consistency across projects. Whether you're a solo developer or part of a large team, mastering the art of packaging in .NET Core is essential for building scalable and maintainable software.

Stay tuned for a detailed video tutorial where we will walk through each step visually, using Visual Studio to demonstrate everything from package creation to implementation.

 


 

Watch this blog on this following video tutorial …….