Home.NET.NET CoreHow to create reusable packages for .NET Core

How to create reusable packages for .NET Core

In this journal blog, we will be looking at how to create reusable packages of code for .NET Core. Reusable packages of code are a great source for developers. It helps them to build and run the projects faster the next time they are building.

NuGet is an open-sourced package manager designed for the Microsoft platform (.NET + .NET Core). It was introduced in 2010 and it defines how packages for .NET and .NET Core are created, hosted, and consumed.

Creating a Package

The package is meant to be something reusable, like a library that we can add a reference to in our existing project. We will be using .NET Core commands in the terminal window to create the package.

Following are the steps taken:

  1. Create a solution directory for our solution to live in
  2. Create the solution file itself
  3. Create a class library type project
  4. Add the class library reference to the solution
  5. Add/Update the code in the library project.
  6. Create a NuGet Package
  7. Installing the package locally
  8. Publishing the package

1. Create a Solution Directory

Let’s create a directory first where our package will reside while developing. You can name your package whatever you want.

mkdir DJPackage
cd DJPackage

2. Create a Solution File

Let’s generate a solution file by using the following command.

dotnet new sln

3. Create a Class library

Next step is to create a class library. This is the main part where the reusable code will reside.

dotnet new classlib -o djlibrary

4. Add the class library to the solution

Now let’s add the new create class library to the solution. This gives the ability to build everything at once among other benefits.

dotnet sln add djlibrary/djlibrary.csproj

5. Add code in the project

Great, now we have our solution, a class library, but the main part is still missing, the code we want other programmers to use.

Let’s open up our project in the VS Code and start writing some code.

code .

The above command is the shortcut to open the Visual Studio Code and open the current directory as the project directory inside VSCode.

The first thing which we are going to do is rename the Class1.cs to Start.cs and write a very simple method which will return the greeting message.

namespace djlibrary {
     public class Start {
         public string greetMessage(string msg) {
             return "Hello, Message for you: " + msg;
         }
     }
 }

6. Create a NuGet package

Good, now that we have a small working piece of code ready, lets turn this into a NuGet package.

The following steps are needed to be taken care of while creating a NuGet package:

  1. Add some meta information to the library project
  2. Invoke the pack command, this will create the package

Meta information are the things like name, author, company and so on. We will need these entries in the djlibrary.csproj file under the XML tag PropertyGroup.

<TargetFramework>netcoreapp2.2</TargetFramework>
<PackageId>dj-greetmessage</PackageId>
<Version>1.0.0</Version>
<Authors>dj</Authors>
<Company>Developers Journal</Company>

The name of the package will be determined by PackageId + Version.

Next let’s navigate to our library directory and create our package by typing in the following command:

cd djlibrary
dotnet pack

The pack command is responsible for creating a NuGet package of our library project. The package is created under bin/debug folder by the name as dj-greetmessage.1.0.0.nupkg.

7. Install the package locally

Before we publish our package to nuget.org we need to test the package locally first because we don’t to push any buggy package.

Well to test the newly created package we need to create a new project to test it on. Let’s create a new console application

dotnet new console -o ConsoleApp

Now let’s add this project to the solution

dotnet sln add ConsoleApp/ConsoleApp.csproj

Next, lets now install our package. We do this in two steps:

  1. Point out the local source, this is about instructing the target project where this package can be found on our computer, so if it fails to find it on NuGet it knows to look at your computer next.
  2. Add the package, this will install the package in the target project

Point out the local source

We need to go into the target projects .csproj file. We want to test out our NuGet package on our console app called ConsoleApp so we open up ConsoleApp.csproj and under PropertyGroup we add a tag called RestoreSources. Here we point out both the path to our local NuGet package and the NuGet stream. It should look like so:

<RestoreSources>$(RestoreSources);absolute-path-to-solution/djlibrary/bin/Debug;https://api.nuget.org/v3/index.json</RestoreSources>

We need to replace absolute-path-to-solution/djlibrary/bin/Debug above with the absolute path to where our package is located.

Add the package

Now that we pointed out where NuGet can find our package we are ready to install it.

This is as simple as calling (from the solution root):

dotnet add ConsoleApp package dj-greetmessage

dj-greetmessage is the name of the package we have given in the meta tags.

Inspecting our ConsoleApp.csproj file we can see that we now get the following entry:

<PackageReference Include="dj-greetmessage" Version="1.0.0" />

Now lets try out our installed package. Change Program.cs in your app project to the following code:

using System;
using djlibrary;

namespace ConsoleApp
{
  class Program
  {
    static void Main(string[] args)
    {
        var start = new Start();

        Console.WriteLine(start.greetMessage("This is a message for PackageManager."));
    }
  }
}

8. Publishing your package

Ok, now that we have spent some time testing our package locally, we want our package to be published to the NuGet repository nuget.org.

We need the following:

  1. NuGet credentials
  2. Invoke the publish command

Create an account – NuGet credentials

Go to nuget.org and create an account by entering an email and username and password. Once all that is done, we need to create a key by clicking at the username at the top right corner page then you select API Keys.

On the API Keys page follow the steps:

  1. Click the + Create
  2. Fill in Key Name
  3. On Selected Scopes check Push.
  4. On the field Glob Pattern just enter a *.
  5. The last step is clicking the blue Create button.

Scroll down the manage now and find the Manage section. Your new key should exist here. Press the Copy button and your key should now be in your clipboard.

Invoke the publish command

Now the main fun part begins, the package is built, key has been obtained and now we are just one command away from pushing our package to nuget.org.

The command we need looks like this:

dotnet nuget push [package name].nupkg -k [API key] -s https://api.nuget.org/v3/index.json

Move to the djlibrary/bin/Debug directory, replace with your values above and run the command in the terminal.

You should now find your package at:

https://www.nuget.org/packages/dj-greetmessage/1.0.0

Just a point to remember that the package doesn’t do much beside the greet message. Try to improve from this point on. If the package is useful for you then it might be useful to someone else who is looking for the same solutions as like you.

RELATED ARTICLES

Most Popular