Microservice architecture or microservices is a method of developing software applications as a suite of independently deployable, small, modular services in which each service runs a unique process and communicates through a well-defined, lightweight mechanism to serve a business goal.
One of the key features of this pattern is to build up small efficient teams that are individually responsible for developing, release, testing and maintenance of a particular microservice. Thus there will always be a problem of duplicate codes across repositories or across teams.
In this post we will be talking about how we can write common codes like common class libraries in ASP.NET based microservices and how to share them across services so that it can be used by all the teams and we can follow the DRY principle.
Prerequisites
- NET Core 1.1 SDK you can download it from here.
Lets begin by creating a class library in .Net core which can be reused by other projects.
Step 1 - Create a .Net core class library
We will be using the dotnet cli tool to create our class library project. If you have visual studio 2017 installed, you can use the .NET core templates as well.
- >> dotnet new classlib -n CommonUtil
The above command will create a .NET core class library and name it CommonUtil.
For more options while using the dotnet cli tool please visit here.
Step 2 - Build and package your class library
Now comes the main part of converting our .NET core class library into a nuget package.
NoteFor those who are new to Nuget, Nuget is the package manager for the Microsoft development platform including .NET. The NuGet client tools provide the ability to produce and consume packages. The NuGet Gallery is the central package repository used by all package authors and consumers.
To know more about Nuget please visit here.
Now assuming that you are in the root folder where you have created the project earlier i.e CommonUtil, we will run the following commands.
- >> dotnet restore
- >> dotnet pack --output nupkgs
This will create a nuget package out of our class library and put the .nupkgfile in the output folder mentioned in the command. Since we have not mentioned the — no-build flag in the dotnet pack command, pack will 1st build the project and then create the .nupkg file.
For more information about the dotnet pack command please visit here.
Step 3 - Versioning the package
The above build step will by default create a package with the file name <project_name>.1.0.0.nupkg, in our case it is CommonUtil.1.0.0.nupkg. So if we see that 1.0.0 i.e the default version of our package has been added to the package name by the dotnet cli tool.
How to specify the package version while creating the package?
We will need to add few configuration to give explicit versioning of our .Net core library package.



Join the conversation! Your thoughts help the community grow.