【.Net Core從零開始前后端分離】(四)——倉儲+服務+抽象接口模式


前言

這一章節學習后端項目的分層,主要分為API、Models、倉儲層、服務層

各層之間的調用關系:

除了項目對外暴露的是 Api 展示層,和核心的實體 Model 層外,

倉儲模塊(作為一個數據庫管理員,直接操作數據庫,實體模型):

BaseRepository(基類倉儲) 繼承實現了 接口IBaseRepository,這里放公共的方法,
AdvertisementRepostitory 繼承 BaseRepository , IAdvertisementRepository

Service模塊(處理業務邏輯,可以直接使用ViewModel視圖模型):

BaseService 調用 BaseRepository,同時繼承 IBaseService
AdvertisementServices 繼承 BaseServices , IAdvertisementServices

先把分層創建好
選擇解決方案--添加-新建項目-選擇類庫(.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);
    }

運行查看結果

總結

 今天學習了后端整體項目的搭建,結構以及調用

Github

https://github.com/Nick-Hoper/Blog.Core.Demo.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM