Three Tier Architecture In ASP.NET Core 6 Web API

Introduction

In this article, we'll look at three-tier architecture and how to incorporate the Data Access Layer and Business Access Layer into a project, as well as how these layers interact.

Project Structure

We use a three-tier architecture in this project, with a data access layer, a business access layer, and an application presentation layer.

Three Tier Architecture in Asp.net Core 6 Web API

Presentation Layer (PL)

The Presentation layer is the top-most layer of the 3-tier architecture, and its major role is to display the results to the user, or to put it another way, to present the data that we acquire from the business access layer and offer the results to the front-end user.

Business Access Layer (BAL)

The logic layer interacts with the data access layer and the presentation layer to process the activities that lead to logical decisions and assessments. This layer's primary job is to process data between other layers.

Data Access Layer (DAL)

The main function of this layer is to access and store the data from the database and the process of the data to business access layer data goes to the presentation layer against user request.

Three Tier Architecture in Asp.net Core 6 Web API

Steps to follow for configuring these layers,

  • Add the Class Library project of Asp.net for Data Access Layer
  • Right Click on the project and then go to the add the new project window and then add the Asp.net Core class library project.

    Three Tier Architecture in Asp.net Core 6 Web API
  • After Adding the Data Access layer project now, we will add the Business access layer folder
  • Add the Class library project of Asp.Net Core for Business Access
  • Right Click on the project and then go to the add the new project window and then add the Asp.net Core class library project.

    Three Tier Architecture in Asp.net Core 6 Web API

After adding the business access layer and data access layer, we must first add the references of the Data Access layer and Business Access layer, so that the project structure can be seen.

Three Tier Architecture in Asp.net Core 6 Web API

As you can see, our project now has a Presentation layer, Data Access Layer, and Business Access layer.

Add the References of the Project

Now, in the Presentation Layer, add the references to the Data Access Layer and the Business Access Layer.

Right Click on the Presentation layer and then click on add => project Reference

Three Tier Architecture in Asp.net Core 6 Web API

Add the References by Checking both the checkboxes

Three Tier Architecture in Asp.net Core 6 Web API

References have been added for both DAL and BAL

Three Tier Architecture in Asp.net Core 6 Web API

Now we'll add the Data Access layer project references to the Business layer.

  • Right Click on the Business access layer and then Click Add Button => Project References

Three Tier Architecture in Asp.net Core 6 Web API

“Remember that we have included the DAL and BAL references in the project, so don't add the Presentation layer references again in the business layer. We only need the DAL Layer references in the business layer”

Three Tier Architecture in Asp.net Core 6 Web API

Project References of DAL Has been Added in BAL Layer

Three Tier Architecture in Asp.net Core 6 Web API

Data Access Layer

The Data Access Layer contains methods that assist the Business Access Layer in writing business logic, whether the functions are linked to accessing or manipulating data. The Data Access Layer's major goal is to interface with the database and the Business Access Layer in our project.

The structure will be like this.

Three Tier Architecture in Asp.net Core 6 Web API

In this layer we have the following folders. Add these folders to your Data access layer

  • Contacts
  • Data
  • Migrations
  • Models
  • Repositories

Contacts

In the Contract Folder, we define the interface that has the following function that performs the desired functionalities with the database like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JWTTokenAuthInAspNet6_DAL.Contracts {
    public interface IRepository < T > {
        public Task < T > Create(T _object);
        public void Delete(T _object);
        public void Update(T _object);
        public IEnumerable < T > GetAll();
        public T GetById(int Id);
    }
}

Three Tier Architecture in Asp.net Core 6 Web API

Data

In the Data folder, we have Db Context Class this class is very important for accessing the data from the database

Three Tier Architecture in Asp.net Core 6 Web API

Migrations

The Migration folder contains information on all the migrations we performed during the construction of this project. The Migration folder contains information on all the migrations we performed during the construction of this project.

Models

Our application models, which contain domain-specific data, and business logic models, which represent the structure of the data as public attributes, business logic, and methods, are stored in the Model folder.

Three Tier Architecture in Asp.net Core 6 Web API

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JWTTokenAuthInAspNet6_DAL.Models
{
    public class AppUser: IdentityUser
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? AccountType { get; set; }
        public string? PhoneNo { get; set; }
        public string? Password { get; set; }
        public string? ShopName { get; set; }
        public string? BusinessType { get; set; }
        public string? UserRole { get; set; }
        public bool? IsDeleted { get; set; }
    }
}

Repositors

In the Repository folder, we add the repositories classes against each model. We write the CRUD function that communicates with the database using the entity framework. We add the repository class that inherits our Interface that is present in our contract folder.

Three Tier Architecture in Asp.net Core 6 Web API

using JWTTokenAuthInAspNet6_DAL.Contracts;
using JWTTokenAuthInAspNet6_DAL.Data;
using JWTTokenAuthInAspNet6_DAL.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JWTTokenAuthInAspNet6_DAL.Repositories {
    public class RepositoryAppUser: IRepository < AppUser > {
        private readonly AppDbContext _appDbContext;
        private readonly ILogger _logger;
        public RepositoryAppUser(ILogger < AppUser > logger) {
            _logger = logger;
        }
        public async Task < AppUser > Create(AppUser appuser) {
            try {
                if (appuser != null) {
                    var obj = _appDbContext.Add < AppUser > (appuser);
                    await _appDbContext.SaveChangesAsync();
                    return obj.Entity;
                } else {
                    return null;
                }
            } catch (Exception) {
                throw;
            }
        }
        public void Delete(AppUser appuser) {
            try {
                if (appuser != null) {
                    var obj = _appDbContext.Remove(appuser);
                    if (obj != null) {
                        _appDbContext.SaveChangesAsync();
                    }
                }
            } catch (Exception) {
                throw;
            }
        }
        public IEnumerable < AppUser > GetAll() {
            try {
                var obj = _appDbContext.AppUsers.ToList();
                if (obj != null) return obj;
                else return null;
            } catch (Exception) {
                throw;
            }
        }
        public AppUser GetById(int Id) {
            try {
                if (Id != null) {
                    var Obj = _appDbContext.AppUsers.FirstOrDefault(x => x.Id == Id);
                    if (Obj != null) return Obj;
                    else return null;
                } else {
                    return null;
                }
            } catch (Exception) {
                throw;
            }
        }
        public void Update(AppUser appuser) {
            try {
                if (appuser != null) {
                    var obj = _appDbContext.Update(appuser);
                    if (obj != null) _appDbContext.SaveChanges();
                }
            } catch (Exception) {
                throw;
            }
        }
    }
}

Business Access Layer

The business layer communicates with the data access layer and the presentation layer logic layer process the actions that make the logical decision and evaluations the main function of this layer is to process the data between surrounding layers.

Our Structure of the project in the Business Access Layer will be like this.

Three Tier Architecture in Asp.net Core 6 Web API

In this layer we will have two folders

  • Extensions Method Folder
  • And Services Folder

In the business access layer, we have our services that communicate with the surrounding layers like the data layer and Presentation Layer.

Services

Services define the application's business logic. We develop services that interact with the data layer and move data from the data layer to the presentation layer and from the presentation layer to the data access layer.

Example

using JWTTokenAuthInAspNet6_DAL.Contracts;
using JWTTokenAuthInAspNet6_DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JWTTokenAuthInAspNet6_BAL.Services {
    public class ServiceAppUser {
        public readonly IRepository < AppUser > _repository;
        public ServiceAppUser(IRepository < AppUser > repository) {
            _repository = repository;
        }
        //Create Method 
        public async Task < AppUser > AddUser(AppUser appUser) {
            try {
                if (appUser == null) {
                    throw new ArgumentNullException(nameof(appUser));
                } else {
                    return await _repository.Create(appUser);
                }
            } catch (Exception) {
                throw;
            }
        }
        public void DeleteUser(int Id) {
            try {
                if (Id != 0) {
                    var obj = _repository.GetAll().Where(x => x.Id == Id).FirstOrDefault();
                    _repository.Delete(obj);
                }
            } catch (Exception) {
                throw;
            }
        }
        public void UpdateUser(int Id) {
            try {
                if (Id != 0) {
                    var obj = _repository.GetAll().Where(x => x.Id == Id).FirstOrDefault();
                    if (obj != null) _repository.Update(obj);
                }
            } catch (Exception) {
                throw;
            }
        }
        public IEnumerable < AppUser > GetAllUser() {
            try {
                return _repository.GetAll().ToList();
            } catch (Exception) {
                throw;
            }
        }
    }
}

Presentation layer

The top-most layer of the 3-Tier architecture is the Presentation layer the main function of this layer is to give the results to the user or in simple words to present the data that we get from the business access layer and give the results to the front-end user.

In the presentation layer, we have the default template of the asp.net core application here OUR structure of the application will be like 

Three Tier Architecture in Asp.net Core 6 Web API

The presentation layer is responsible to give the results to the user against every HTTP request. Here we have a controller that is responsible for handling the HTTP request and communicates with the business layer against each HTTP request get the get data from the associated layer and then present it to the User.

Advantages of 3-Tier Architecture

  • It makes the logical separation between the presentation layer, business layer, and data layer.
  • Migration to the new environment is fast.
  • In This Model, Each tier is independent so we can set the different developers on each tier for the fast development of applications
  • Easy to maintain and understand the large-scale applications
  • The business layer is in between the presentation layer and data layer the application is more secured because the client will not have direct access to the database.
  • The process data that is sent from the business layer is validated at this level.
  • The Posted data from the presentation layer will be validated at the business layer before Inserting or Updating the Database
  • Database security can be provided at BAL Layer
  • Define the business logic one in the BAL Layer and then share among the other components at the presentation layer
  • Easy to Appy for Object-oriented Concepts
  • Easy to update the data provided quires at DAL Layer

Dis-Advantages of 3-Tier Architecture

  • It takes a lot of time to build the small part of the application
  • Need Good understanding of Object-Oriented programming

Conclusion

In this article, we have learned about 3-tier Architecture and how the three-layer exchange data between them how we can add the Data Access Layer Business access layer in the project, and studied how these layers communicate with each other.

In the next article, we will develop the project using 3-Tier Architecture for JWT Token Authentication in ASP.net Core Web API.

“Happy Coding”