Creating and Referencing Class Libraries in ASP.NET Core

AZHARUL | 14-Nov-2024 08:34:39 PM | Time to read: 6 Min

In this blog, I'll take you through one of the most practical approaches in real-world software development: creating and referencing class libraries in ASP.NET Core. This isn't just about theory—it's about building a structured, maintainable, and scalable application like professionals do.

By the end of this blog, you'll understand how to separate business logic, data access, and common utilities into class libraries and integrate them seamlessly into an ASP.NET Core MVC project.

Let's dive in and build something amazing!

 

In modern software development, modular design is essential to create flexible, maintainable, and scalable applications. .NET Core’s class library structure provides a powerful way to organize and reuse code across projects. This blog walks through the steps to create a main project (InventoryManagement) along with three supporting class libraries (DataAccessLibrary, BusinessLogicLibrary, and CommonUtilities). We’ll show how to structure these libraries effectively, with real-world examples and tips to guide you. Perfect for developers working on enterprise-level applications, this blog leverages Visual Studio, making it easy to follow for developers at any level.

 

Why Use Class Libraries in .NET Core?

Class libraries help modularize an application, promoting clean architecture and separation of concerns. By isolating data access, business logic, and utilities into separate libraries, we can create a flexible and reusable code structure, ideal for real-world applications. In this example, we’ll create class libraries to handle inventory data, business rules, and common utility functions that can be shared across different parts of the application.

 

Setting Up the Project

For this blog, we’ll create a solution named InventoryManagement, containing multiple projects:

  • InventoryManagement (Main MVC Project)
  • DataAccessLibrary for data management
  • BusinessLogicLibrary for business rules
  • CommonUtilities for shared utilities

 

Creating the Main Project (InventoryManagement)

This project will serve as the core of your application, handling requests and managing the connections between the business logic and data access layers.

  • Right-click on the solution > Add > New Project > ASP.NET Core Web App.
  • Name it InventoryManagement.

 

Creating the Data Access Library (DataAccessLibrary)

DataAccessLibrary is where all data-related classes, models, and repository interfaces are stored.

  1. Right-click on the solution > Add > New Project > Class Library (.NET Core).
  2. Name it DataAccessLibrary.
Code Example

Inside DataAccessLibrary, create a Product model and IProductRepository interface for managing products.

namespace DataAccessLibrary.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public double Price { get; set; }
    }
}

namespace DataAccessLibrary.Repositories
{
    public interface IProductRepository
    {
        List<Product> GetAllProducts();
        void AddProduct(Product product);
        void RemoveProduct(int productId);
    }

    public class ProductRepository : IProductRepository
    {
        private List<Product> _products = new()
        {
            new Product { ProductId = 1, ProductName = "Laptop",Quantity =10, Price = 1200.00 },
            new Product { ProductId = 2, ProductName = "Smartphone",Quantity =15, Price = 800.00 }
        };

        public List<Product> GetAllProducts() => _products;
        public void AddProduct(Product product) => _products.Add(product);
        public void RemoveProduct(int productId) => _products.RemoveAll(p => p.ProductId == productId);
    }
}

 

Creating the Business Logic Library (BusinessLogicLibrary)

BusinessLogicLibrary contains service classes for business operations.

· Right-click on the solution > Add > New Project > Class Library (.NET Core).

·  Name it BusinessLogicLibrary.

 

Referencing DataAccessLibrary in BusinessLogicLibrary

 Reference DataAccessLibrary in BusinessLogicLibrary to allow the service classes to access data.

  1. Right-click BusinessLogicLibrary > Add > Project Reference.
  2. Select DataAccessLibrary.

 

Example Code in BusinessLogicLibrary

In BusinessLogicLibrary, create a service class called ProductService that interacts with ProductRepository.

using DataAccessLibrary.Models;
using DataAccessLibrary.Repositories;

namespace BusinessLogicLibrary.Services
{
    public interface IProductService
    {
        void AddNewProduct(Product product);
        List<Product> GetAllProducts();
        void RemoveProduct(int productId);
    }

    public class ProductService : IProductService
    {
        private readonly IProductRepository _productRepository;
        public ProductService(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        public void AddNewProduct(Product product)
        {
            _productRepository.AddProduct(product);
        }

        public List<Product> GetAllProducts()
        {
            return _productRepository.GetAllProducts();
        }

        public void RemoveProduct(int productId)
        {
            _productRepository.RemoveProduct(productId);
        }
    }
}

 

Referencing BusinessLogicLibrary in InventoryManagement

 Reference BusinessLogicLibrary in InventoryManagement to allow the Controller classes to access Service classes methods.

  1. Right-click InventoryManagement > Add > Project Reference.
  2. Select BusinessLogicLibrary.

 

In InventoryManagement, we’ll create a controller name HomeController to interact with ProductService, we will inject IProductService into the controller to access the business logic.

Example Code in InventoryManagement
using BusinessLogicLibrary.Services;
using DataAccessLibrary.Models;
using Microsoft.AspNetCore.Mvc;

namespace InventoryManagement.Controllers
{
    public class HomeController : Controller
    {
        private readonly IProductService _productService;
        public HomeController(IProductService productService)
        {
            _productService = productService;
        }

        public IActionResult Index()
        {
            var products = _productService.GetAllProducts();
            return View(products);
        }

        public IActionResult AddProduct(Product product)
        {
            _productService.AddNewProduct(product);
            return RedirectToAction("Index");
        }
    }
}

This setup allows InventoryManagement to access data and business logic through dependency injection, following the layered structure where data flows from DataAccessLibrary to BusinessLogicLibrary and is used by InventoryManagement.

 

Adding a Common Utilities Library

Create a library called CommonUtilities to hold reusable utilities.

namespace CommonUtilities.DateUtility
{
    public static class DateUtility
    {
        public string FormatDate(DateTime date)
        {
        	return date.ToString("dd-MMM-yyyy");
        }
    }
}

Add CommonUtilities as a reference to both BusinessLogicLibrary and InventoryManagement.

 

Configuring DI(Dependency Injection) in Program.cs in the Main Project

Open Program.cs in the InventoryManagement project and register ProductRepository and ProductService:

using BusinessLogicLibrary.Services;
using DataAccessLibrary.Repositories;

var builder = WebApplication.CreateBuilder(args);


// --------------Register services with the DI container-------------
builder.Services.AddScoped<IProductRepository,ProductRepository>();
builder.Services.AddScoped<IProductService,ProductService>();

builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

 

Class libraries in .NET Core offer a clean, modular structure for developing robust applications. By following the patterns outlined here, you’ll be equipped to design, implement, and test real-life applications with a scalable, maintainable code structure.

 

I hope this blog not only clarified your doubts but also inspired you to adopt better practices in your development projects. Remember, clean and modular code is the hallmark of a great developer!

 

If you found this blog helpful, please share it with your peers and colleagues. Don't forget to subscribe to our YouTube channel(Visit Codexoom on YouTube) for more tutorials on ASP.NET Core and professional software development tips!

Thank you for joining us, and as always, happy coding! Until next time, stay curious and keep building amazing things. Take care!