【.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

posted @ 2020-12-23 17:48  凌云幽雨  阅读(2338)  评论(4编辑  收藏  举报