【.Net Core從零開始前後端分離】(四)——倉儲+服務+抽象介面模式
前言
這一章節學習後端專案的分層,主要分為API、Models、倉儲層、服務層
各層之間的呼叫關係:
除了專案對外暴露的是 Api 展示層,和核心的實體 Model 層外,
倉儲模組(作為一個數據庫管理員,直接操作資料庫,實體模型):
BaseRepository(基類倉儲) 繼承實現了 介面IBaseRepository,這裡放公共的方法,
AdvertisementRepostitory 繼承 BaseRepository
Service模組(處理業務邏輯,可以直接使用ViewModel檢視模型):
BaseService 呼叫 BaseRepository,同時繼承 IBaseService
AdvertisementServices 繼承 BaseServices
先把分層建立好
選擇解決方案--新增-新建專案-選擇類庫(.Net Core)-Blog.Core.Repository/Blog.Core.IRepository/Blog.Core.IService/Blog.Core.Service
建立實體Model資料層
其中,
Models資料夾中,存放的是整個專案的資料庫表實體類。
VeiwModels資料夾,是存放的DTO實體類,在開發中,一般介面需要接收資料,返回資料。
MessageModel和TableModel 通用返回格式
設計倉儲介面與其實現類
建立Blog.Core.IRepository和 Blog.Core.Repository 倉儲層:
這裡簡單說下倉儲層:repository就是一個管理資料持久層的,它負責資料的CRUD(Create, Read, Update, Delete) service layer是業務邏輯層,它常常需要訪問repository層。有網友這麼說:Repository(倉儲):協調領域和資料對映層,利用類似與集合的介面來訪問領域物件。Repository 是一個獨立的層,介於領域層與資料對映層(資料訪問層)之間。它的存在讓領域層感覺不到資料訪問層的存在,它提供一個類似集合的介面提供給領域層進行領域物件的訪問。Repository 是倉庫管理員,領域層需要什麼東西只需告訴倉庫管理員,由倉庫管理員把東西拿給它,並不需要知道東西實際放在哪。
在 IAdvertisementRepository.cs 中,新增一個求和介面
public interface IAdvertisementRepository
{
int Sum(int i, int j);
}
然後再在 AdvertisementRepository.cs 中去實現該介面,記得要新增引用
public class AdvertisementRepository : IAdvertisementRepository
{
public int Sum(int i, int j)
{
return i + j;
}
}
設計服務介面與其實現類
建立 Blog.Core.IServices 和 Blog.Core.Services 業務邏輯層,就是和我們平時使用的三層架構中的BLL層很相似:
Service層只負責將Repository倉儲層的資料進行呼叫,至於如何是與資料庫互動的,它不去管,這樣就可以達到一定程度上的解耦.
這裡在 IAdvertisementServices 中新增介面
namespace Blog.Core.IServices
{
public interface IAdvertisementServices
{
int Sum(int i, int j);
}
}
然後再在 AdvertisementServices 中去實現該介面
public class AdvertisementServices : IAdvertisementServices
{
IAdvertisementRepository dal = new AdvertisementRepository();
public int Sum(int i, int j)
{
return dal.Sum(i, j);
}
}
注意!這裡是引入了三個名稱空間
using Blog.Core.IRepository;
using Blog.Core.IServices;
using Blog.Core.Repository;
建立 Controller 介面呼叫
系統預設的WeatherForecastController刪除,手動新增一個BlogController控制器,可以選擇一個空的API控制器。
接下來,在應用層新增服務層的引用
using Blog.Core.IServices;
using Blog.Core.Services;
然後,改寫Get方法,且只保留一個get方法。否則會導致路由過載
/// <summary>
/// Sum介面
/// </summary>
/// <param name="i">引數i</param>
/// <param name="j">引數j</param>
/// <returns></returns>
[HttpGet]
public int Get(int i, int j)
{
IAdvertisementServices advertisementServices = new AdvertisementServices();
return advertisementServices.Sum(i, j);
}
執行檢視結果
總結
今天學習了後端整體專案的搭建,結構以及呼叫