十年河东,十年河西,莫欺少年穷
学无止境,精益求精
开局一张图,内容全靠编
如下图:
上图是我简单构造的一个NetCore的分层项目,解释如下:
appModel:实体层
appDataInterface:数据访问接口层
appDataService:数据访问接口层的实现层
appLogicInterface:业务逻辑接口层
appLogicService:业务逻辑层的实现层
appWeb:webApi站点
很简单的一个基础的项目构造就这样悄无声息的构建出来了,层次之间的引用,我就不多赘述了。哈哈
然后,我们搞一个接口,如下:
appDataInterface 的 ILoginRepository
using appModel; using System; using System.Collections.Generic; using System.Text; namespace appDataInterface { public interface ILoginRepository { LoginModel UserLogin(string userAccount, string userPassword); } }
appLogicInterface 的 ILoginService
using appModel; using System; using System.Collections.Generic; using System.Text; namespace appLogicInterface { public interface ILoginService { LoginModel UserLogin(string userAccount, string userPassword); } }
再然后,我们搞下接口的实现,如下:
appDataService 的 LoginRepository
using appDataInterface; using appModel; using System; namespace appDataService { public class LoginRepository: ILoginRepository { public LoginModel UserLogin(string userAccount, string userPassword) { return new LoginModel() { userName = "陈大六", userRole = "超级管理员" }; } } }
appLogicService 的 LoginService
using appDataInterface; using appLogicInterface; using appModel; using System; namespace appLogicService { public class LoginService: ILoginService { private readonly ILoginRepository repository; public LoginService(ILoginRepository repository) { this.repository = repository; } /// <summary> /// 用户登录接口 /// </summary> /// <param name="userAccount"></param> /// <param name="userPassword"></param> /// <returns></returns> public LoginModel UserLogin(string userAccount, string userPassword) { return repository.UserLogin(userAccount, userPassword); } } }
注意:业务逻辑层需要依赖注入数据访问层,因此她的构造方法为:
private readonly ILoginRepository repository; public LoginService(ILoginRepository repository) { this.repository = repository; }
最后,我们来写个简单的控制器,如下:
using appLogicInterface; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace appWeb.Controllers { [Route("api/Login")] [ApiController] public class LoginController : ControllerBase { private readonly ILoginService service; public LoginController(ILoginService service) { this.service = service; } [HttpGet("UserLogin")] public IActionResult UserLogin(string userName,string userPassword) { return Ok(service.UserLogin(userName, userPassword)); } } }