Creating and Consuming Dotnet Core 1.1 NuGet Packages Locally
Mar 19, 2017
This is a quick-start guide to creating and consuming a Dotnet Core 1.1 class library locally as a NuGet package. You can then publish your package to the NuGet Gallery. For the purposes of this demo, we will create a library called MathLib to help us identify prime numbers.
Creating the Library
You might be used to running dotnet new -t lib to create an empty class library but that has been deprecated and you can now just pass in the template name as a switch-free argument. We will use the classlib template with the -f netcoreapp1.1 switch to let Dotnet know we are targeting Core 1.1. Let’s create a new folder and create our project:
Let’s restore dependencies using dotnet restore:
If you open your project folder in Visual Studio Code it should look something like this:
Let’s rename Class1.cs to MathHelper.cs and implement the following method to check for prime numbers:
Now if we run dotnet pack, we will get a DLL and a NuGet package:
Note that I’m not running dotnet build because dotnet pack by default first builds the project. You can trigger a pack without a build by passing the --no-build option in to the command line.
Referencing the Package as a Dependency
Now that we have a library with a NuGet package, let’s create a console app that references it:
I omitted the dotnet Core CLI console output for brevity. Let’s open our .csproj file and add a package reference to MathLib:
If we try to restore, we will now get an error:
Note the config file used (in my case /Users/deandavidson/.nuget/NuGet/NuGet.Config) because you will want to edit that to reference a local feed. Create a folder to host your local packages and copy your package from /MathLib/bin/debug to the newly-created folder under the subfolder MathLib. It should look something like this:
Now that we have a local packages folder, let’s edit our global NuGet.Config to search this folder for packages. Simply add a PackageSource with the key of your choice that points to your newly-created folder:
If you don’t want to edit your global config you can edit your project-level config instead. Read this for more information on configuring NuGet. With our packages folder created and NuGet config updated, we should be able to run dotnet restore and see the following:
Now we can reference our MathLib project. Let’s change the contents of Program.cs to the following:
If we run our app we should get the following:
Hopefully this blog post was useful to you. If you truly just want to reference another local project and don’t care about NuGet packages, the Project Reference syntax might be easier (<ProjectReference Include="..\MyOtherProject\MyOtherProject.csproj" />). See Microsoft’s Documentation on the subject for more info.