Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

How to create a shared library in .NET Core?


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

shared library 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.

Table of Content

Why shared code across projects or assemblies?

There are multiple reasons to share code across project or assemblies:

  1. 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.
  2. 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.
  3. Separate development: Separate development of assemblies can be done independently.

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

  1. .Net Standard library: It can be directly shared between applications based on versions match.
  2. 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 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.

ai-Hiring-banner

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.

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.

ai-Hiring-banner

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.

ai-Hiring-banner

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.

ai-Hiring-banner

Figure 4 Create a reference to the library
 


Step 5: Run the application

Set DemoConsole Application as a startup project from solution explorer

ai-Hiring-banner

Figure 5 Set project as a Startup project
 

Run application by pressing CTRL+F5

ai-Hiring-banner

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.

shared library 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.

Table of Content

Why shared code across projects or assemblies?

There are multiple reasons to share code across project or assemblies:

  1. 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.
  2. 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.
  3. Separate development: Separate development of assemblies can be done independently.

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

  1. .Net Standard library: It can be directly shared between applications based on versions match.
  2. 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 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.

ai-Hiring-banner

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.

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.

ai-Hiring-banner

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.

ai-Hiring-banner

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.

ai-Hiring-banner

Figure 4 Create a reference to the library
 


Step 5: Run the application

Set DemoConsole Application as a startup project from solution explorer

ai-Hiring-banner

Figure 5 Set project as a Startup project
 

Run application by pressing CTRL+F5

ai-Hiring-banner

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.

Leave Comments