×

iFour Logo

How to create a shared library in .NET Core?

Kapil Panchal - February 22, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
How to create a shared library in .NET Core?

In a simple application sharing library is a fundamental requirement. The shared library is used so that developers can reuse packages as a library in a project and we can also upload a project to NUGET.org so that other users can download and install these projects into their project using the library.

Why shared code across projects or assemblies?


  • Code Reuse: Shared library enables code reusability by placing code into the library and the developer should not have to re-write the same code for more than one time.

  • Multiple front-ends: Multiple web application can be developed by splitting web assemblies to your project and these all web application uses same data access layer.

  • Separate development: Separate development of assemblies can be done independently.

Planning to hire Java developer for your next project? Your search ends here.

There are two ways to share a library in a mixed development ecosystem:

  • .Net Standard library: It can be directly shared between applications based on versions match.

  • Multi-targeting framework: It uses multi-targeting cross-compiled library for more than one platform.

Share Library through .Net Standard or concept of PCL


.NET standard introduced by Microsoft provides a common standard environment for APIs across Microsoft development system which can be viewed as the successor to Portable class libraries which simplifies the business of targeting different platforms. The .NET standard provides curated sets of APIs when PCLs which are based on the profiles defined by intersecting platform capabilities.

Using this we can create a library that can be referenced by both the .NET framework and .NET Core application. Ensure that the .NET standard Library NuGet package is added to any .NET framework project, which wants to reference a .NET standard library.

There are more than half a dozen versions of the .Net standard and it is not clear which version to target. In the higher version of .Net standard provide a wider range of APIs and in lower version provide a wide range of platform.

.NET standard provides limited support for the .NET framework and each version is supported by a different version. Example- Use .NET standard 1.2 which is available for both .NET core and .NET framework 4.5.2 application. Version support for below 1.3 is pretty sketchy.

Multi-targeting Framework


The main advantage of .NET core is that it can be used or implement cross-platform.

In the bigger development environment, the .NET framework cannot guarantee recent vintage therefore the multi-targeting can provide a wide range of shared libraries. So that developer can compile single project natively for both .NET standard and .NET framework this cost multiple set of compiled output.

In visual studio 2015 multi-targeting is pretty choppy because of Json based old xproj format. Developer can compiler more than one framework but can’t use direct project referenced in .NET framework project. This is difficult, you either had to migrate the target project to the xproject structure or distribute the dependency, neither approach was ideal.

The developer has to manually edit the project file to get it working. Re-loading can be one of the solutions after making any manual change to the framework.

Refer the following example which shows the adjustment of the Target Framework element to get a project to compile for more than one framework.

 
  
net452;netstandard1.3  

             

After compiling the project, you will find two outputs in the BIN folder, one for each specified framework, and create a reference to the shared assembly for the project built with .NET Framework 4.5.2.

NuGet package is a supportive tool for accessing the third-party API. Using NuGet developer can contribute own developed library so that everyone can download and install it and use it in their project.

Let's start with an example:

Let start with creating a blank solution to put the class library project. In Visual studio blank solution serves as a container for one or more projects and you can add related projects to the same solution.

Step 1: Create the blank solution

Open visual studio 2019

Open the start window and choose to create a new project.

In create a new project page, search Blank solutiontemplate in the search box and then Choose Next.

Enter DemoLibrary in the Project name box in Configure your new project page. Then press Create button.

Create a blank solution Figure 1: Create a blank solution

Step 2: Create a class library project.

Add a new “DemoLibrary” named .NET class library project to the solution.

Right-click on the solution and select Add->New Project from Solution Explorer .

Want to create sustainable application for your business? Connect us right now to hire Blockchain developers.

Search Library in Add new project page in the search box. Select C# from the language list, and then select All platforms from the platform list. Select the Class Library template and click on the Next button.

Enter DemoLibrary in the Project name Box on Configure your new project page and click on theNext button.

Create a class libraryFigure 2 Create a class library

Replace Class.cs with the following code and rename with StringLibrary named file and Save the file.

\using System;

namespace DemoLibrary
{
public static class StringLibrary
{
public static bool StartsWithLower(this string str)
{
if (string.IsNullOrWhiteSpace(str))
    return false;

char ch = str[0];
return char.IsLower(ch);
}
}
}
                

The class library DemoLibrary.StringLibrary contains the StringLibrary method. . This method returns a Boolean value when the string starts with a Lower character.Char.IsLower() method returns true if a character is lower.

Select Build->Build solution or press CTR+SHIFT+B to verify that the project compiles without error.

Step 3: Add Console application to the solution

Add a “DemoConsole” console application that uses the class library. This application will prompt the user to enter a string and return true if the string contains a lower character.

Add .Net Console application named it “DemoConsole” to the solution.

Right-click on the solution and select Add->New Project from Solution Explorer..

Search Console in Add new project page in the search box. Select C# from the language list, and then select All platforms from the platform list. Select the Console Application template and click on the Next button.

Enter DemoConsole in the Project name Box on Configure your new project page and click on the Next button.

Create a console application Figure 3 Create a console application

2.Replace Program.cs with the following code:

 
using System;
using DemoLibrary;

namespace DemoConsole
{
class Program
{
static void Main(string[] args)
{
int row = 0;

do
{
if (row == 0 || row >= 25)
ResetConsole();

string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) break;
Console.WriteLine($"Input: {input} {"Begins with lowercase? ",30}: " +
  $"{(input.StartsWithUpper() ? "Yes" : "No")}\n");
row += 3;
} while (true);
return;

// Declare a ResetConsole local method
void ResetConsole()
{
if (row > 0)
{
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
Console.Clear();
Console.WriteLine("\nPress  only to exit; otherwise, enter a string and press :\n");
row = 3;
}
}
}
}

  

The row variable is used to maintain a count number of rows written in console application when its value greater than 25 the code clear console application.

Are You Looking for Dedicated ASP.Net Core Developer ? Your Search ends here.

Step 4: Add a project Reference

Console application cannot access the class library. To access the method of the library, create a project reference to the class library project.

Right-click on DemoConsole project’s Dependency node and select Add project reference in Solution Explorer..

Select DemoLibrary project and click on OK, In the Reference Manager..

Create a reference to the libraryFigure 4 Create a reference to the library

Step 5: Run the application

Set DemoConsole Application as a startup project from solution explorer

Set project as a Startup project

 

Figure 5 Set project as a Startup project

 

Run application by pressing CTRL+F5

Run Application

 

Figure 6 Run Application

 

Conclusion


In this blog, we have discussed how to create the shared library in asp.net core which is used for developers to reuse packages as a library in projects and we have also discussed examples.

How to create a shared library in .NET Core? In a simple application sharing library is a fundamental requirement. The shared library is used so that developers can reuse packages as a library in a project and we can also upload a project to NUGET.org so that other users can download and install these projects into their project using the library. Why shared code across projects or assemblies? Code Reuse: Shared library enables code reusability by placing code into the library and the developer should not have to re-write the same code for more than one time. Multiple front-ends: Multiple web application can be developed by splitting web assemblies to your project and these all web application uses same data access layer. Separate development: Separate development of assemblies can be done independently. Planning to hire Java developer for your next project? Your search ends here. Connect us now There are two ways to share a library in a mixed development ecosystem: .Net Standard library: It can be directly shared between applications based on versions match. Multi-targeting framework: It uses multi-targeting cross-compiled library for more than one platform. Share Library through .Net Standard or concept of PCL .NET standard introduced by Microsoft provides a common standard environment for APIs across Microsoft development system which can be viewed as the successor to Portable class libraries which simplifies the business of targeting different platforms. The .NET standard provides curated sets of APIs when PCLs which are based on the profiles defined by intersecting platform capabilities. Using this we can create a library that can be referenced by both the .NET framework and .NET Core application. Ensure that the .NET standard Library NuGet package is added to any .NET framework project, which wants to reference a .NET standard library. There are more than half a dozen versions of the .Net standard and it is not clear which version to target. In the higher version of .Net standard provide a wider range of APIs and in lower version provide a wide range of platform. .NET standard provides limited support for the .NET framework and each version is supported by a different version. Example- Use .NET standard 1.2 which is available for both .NET core and .NET framework 4.5.2 application. Version support for below 1.3 is pretty sketchy. Multi-targeting Framework The main advantage of .NET core is that it can be used or implement cross-platform. In the bigger development environment, the .NET framework cannot guarantee recent vintage therefore the multi-targeting can provide a wide range of shared libraries. So that developer can compile single project natively for both .NET standard and .NET framework this cost multiple set of compiled output. In visual studio 2015 multi-targeting is pretty choppy because of Json based old xproj format. Developer can compiler more than one framework but can’t use direct project referenced in .NET framework project. This is difficult, you either had to migrate the target project to the xproject structure or distribute the dependency, neither approach was ideal. Read More: Class Library In .net Core The developer has to manually edit the project file to get it working. Re-loading can be one of the solutions after making any manual change to the framework. Refer the following example which shows the adjustment of the Target Framework element to get a project to compile for more than one framework.   net452;netstandard1.3 After compiling the project, you will find two outputs in the BIN folder, one for each specified framework, and create a reference to the shared assembly for the project built with .NET Framework 4.5.2. NuGet package is a supportive tool for accessing the third-party API. Using NuGet developer can contribute own developed library so that everyone can download and install it and use it in their project. Let's start with an example: Let start with creating a blank solution to put the class library project. In Visual studio blank solution serves as a container for one or more projects and you can add related projects to the same solution. Step 1: Create the blank solution Open visual studio 2019 Open the start window and choose to create a new project. In create a new project page, search Blank solutiontemplate in the search box and then Choose Next. Enter DemoLibrary in the Project name box in Configure your new project page. Then press Create button. Figure 1: Create a blank solution Step 2: Create a class library project. Add a new “DemoLibrary” named .NET class library project to the solution. Right-click on the solution and select Add->New Project from Solution Explorer . Want to create sustainable application for your business? Connect us right now to hire Blockchain developers. Reach out us Search Library in Add new project page in the search box. Select C# from the language list, and then select All platforms from the platform list. Select the Class Library template and click on the Next button. Enter DemoLibrary in the Project name Box on Configure your new project page and click on theNext button. Figure 2 Create a class library Replace Class.cs with the following code and rename with StringLibrary named file and Save the file. \using System; namespace DemoLibrary { public static class StringLibrary { public static bool StartsWithLower(this string str) { if (string.IsNullOrWhiteSpace(str)) return false; char ch = str[0]; return char.IsLower(ch); } } } The class library DemoLibrary.StringLibrary contains the StringLibrary method. . This method returns a Boolean value when the string starts with a Lower character.Char.IsLower() method returns true if a character is lower. Select Build->Build solution or press CTR+SHIFT+B to verify that the project compiles without error. Step 3: Add Console application to the solution Add a “DemoConsole” console application that uses the class library. This application will prompt the user to enter a string and return true if the string contains a lower character. Add .Net Console application named it “DemoConsole” to the solution. Right-click on the solution and select Add->New Project from Solution Explorer.. Search Console in Add new project page in the search box. Select C# from the language list, and then select All platforms from the platform list. Select the Console Application template and click on the Next button. Enter DemoConsole in the Project name Box on Configure your new project page and click on the Next button. Figure 3 Create a console application 2.Replace Program.cs with the following code:   using System; using DemoLibrary; namespace DemoConsole { class Program { static void Main(string[] args) { int row = 0; do { if (row == 0 || row >= 25) ResetConsole(); string input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) break; Console.WriteLine($"Input: {input} {"Begins with lowercase? ",30}: " + $"{(input.StartsWithUpper() ? "Yes" : "No")}\n"); row += 3; } while (true); return; // Declare a ResetConsole local method void ResetConsole() { if (row > 0) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } Console.Clear(); Console.WriteLine("\nPress only to exit; otherwise, enter a string and press :\n"); row = 3; } } } } The row variable is used to maintain a count number of rows written in console application when its value greater than 25 the code clear console application. Are You Looking for Dedicated ASP.Net Core Developer ? Your Search ends here. Contact us Step 4: Add a project Reference Console application cannot access the class library. To access the method of the library, create a project reference to the class library project. Right-click on DemoConsole project’s Dependency node and select Add project reference in Solution Explorer.. Select DemoLibrary project and click on OK, In the Reference Manager.. Figure 4 Create a reference to the library Step 5: Run the application Set DemoConsole Application as a startup project from solution explorer   Figure 5 Set project as a Startup project   Run application by pressing CTRL+F5   Figure 6 Run Application   Conclusion In this blog, we have discussed how to create the shared library in asp.net core which is used for developers to reuse packages as a library in projects and we have also discussed examples.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
How Power BI Addresses Spreadsheet Challenges?
How Power BI Addresses Spreadsheet Challenges?

Data-driven businesses remain profitable in the long run; the key reason is that they adopted data analytics early in their phase. It's no secret that companies generate a massive...

10 Legal Practice Management Tools Integrated with Power Apps
10 Legal Practice Management Tools Integrated with Power Apps

There’s a major transformation happening in the legal field, as legal consultants are turning their attention to new technology. Facts say that 48% of legal professionals have raised...

Power Apps Solving 13 Legal Challenges
Power Apps Solving 13 Legal Challenges

There is a common misconception that bringing technology into the legal field won't be effective as this profession relies heavily on evidence and facts. However, if you look at it...