ABP入门系列(4)——创建应用服务
ABP入門系列目錄——學(xué)習(xí)Abp框架之實(shí)操演練
1. 解釋下應(yīng)用服務(wù)層
應(yīng)用服務(wù)用于將領(lǐng)域(業(yè)務(wù))邏輯暴露給展現(xiàn)層。展現(xiàn)層通過傳入DTO(數(shù)據(jù)傳輸對(duì)象)參數(shù)來調(diào)用應(yīng)用服務(wù),而應(yīng)用服務(wù)通過領(lǐng)域?qū)ο髞韴?zhí)行相應(yīng)的業(yè)務(wù)邏輯并且將DTO返回給展現(xiàn)層。因此,展現(xiàn)層和領(lǐng)域?qū)訉⒈煌耆綦x開來。
以下幾點(diǎn),在創(chuàng)建應(yīng)用服務(wù)時(shí)需要注意:
2. 定義ITaskAppService接口
2.1. 先來看看定義的接口
?
public interface ITaskAppService : IApplicationService{GetTasksOutput GetTasks(GetTasksInput input);void UpdateTask(UpdateTaskInput input);int CreateTask(CreateTaskInput input);Task<TaskDto> GetTaskByIdAsync(int taskId);TaskDto GetTaskById(int taskId);void DeleteTask(int taskId);IList<TaskDto> GetAllTasks();}觀察方法的參數(shù)及返回值,大家可能會(huì)發(fā)現(xiàn)并未直接使用Task實(shí)體對(duì)象。這是為什么呢?因?yàn)檎宫F(xiàn)層與應(yīng)用服務(wù)層是通過Data Transfer Object(DTO)進(jìn)行數(shù)據(jù)傳輸。
2.2. 為什么需要通過dto進(jìn)行數(shù)據(jù)傳輸?
總結(jié)來說,使用DTO進(jìn)行數(shù)據(jù)傳輸具有以下好處。
- 數(shù)據(jù)隱藏
- 序列化和延遲加載問題
- ABP對(duì)DTO提供了約定類以支持驗(yàn)證
- 參數(shù)或返回值改變,通過Dto方便擴(kuò)展
了解更多詳情請(qǐng)參考:
ABP框架 - 數(shù)據(jù)傳輸對(duì)象
2.3. Dto規(guī)范 (靈活應(yīng)用)
- ABP建議命名輸入/輸出參數(shù)為:MethodNameInput和MethodNameOutput
- 并為每個(gè)應(yīng)用服務(wù)方法定義單獨(dú)的輸入和輸出DTO(如果為每個(gè)方法的輸入輸出都定義一個(gè)dto,那將有一個(gè)龐大的dto類需要定義維護(hù)。一般通過定義一個(gè)公用的dto進(jìn)行共用)
- 即使你的方法只接受/返回一個(gè)參數(shù),也最好是創(chuàng)建一個(gè)DTO類
- 一般會(huì)在對(duì)應(yīng)實(shí)體的應(yīng)用服務(wù)文件夾下新建Dtos文件夾來管理Dto類。
3. 定義應(yīng)用服務(wù)接口需要用到的DTO
3.1. 先來看看TaskDto的定義
?
namespace LearningMpaAbp.Tasks.Dtos {/// <summary>/// A DTO class that can be used in various application service methods when needed to send/receive Task objects./// </summary>public class TaskDto : EntityDto{public long? AssignedPersonId { get; set; }public string AssignedPersonName { get; set; }public string Title { get; set; }public string Description { get; set; }public DateTime CreationTime { get; set; }public TaskState State { get; set; }//This method is just used by the Console Application to list taskspublic override string ToString(){return string.Format("[Task Id={0}, Description={1}, CreationTime={2}, AssignedPersonName={3}, State={4}]",Id,Description,CreationTime,AssignedPersonId,(TaskState)State);}} }該TaskDto直接繼承自EntityDto,EntityDto是一個(gè)通用的實(shí)體只定義Id屬性的簡(jiǎn)單類。直接定義一個(gè)TaskDto的目的是為了在多個(gè)應(yīng)用服務(wù)方法中共用。
3.2. 下面來看看GetTasksOutput的定義
就是直接共用了TaskDto。
?
public class GetTasksOutput{public List<TaskDto> Tasks { get; set; }}3.3. 再來看看CreateTaskInput、UpdateTaskInput
?
public class CreateTaskInput{public int? AssignedPersonId { get; set; }[Required]public string Description { get; set; }[Required]public string Title { get; set; }public TaskState State { get; set; }public override string ToString(){return string.Format("[CreateTaskInput > AssignedPersonId = {0}, Description = {1}]", AssignedPersonId, Description);}}?
/// <summary>/// This DTO class is used to send needed data to <see cref="ITaskAppService.UpdateTask"/> method./// /// Implements <see cref="ICustomValidate"/> for additional custom validation./// </summary>public class UpdateTaskInput : ICustomValidate{[Range(1, Int32.MaxValue)] //Data annotation attributes work as expected.public int Id { get; set; }public int? AssignedPersonId { get; set; }public TaskState? State { get; set; }[Required]public string Title { get; set; }[Required]public string Description { get; set; }//Custom validation method. It's called by ABP after data annotation validations.public void AddValidationErrors(CustomValidationContext context){if (AssignedPersonId == null && State == null){context.Results.Add(new ValidationResult("Both of AssignedPersonId and State can not be null in order to update a Task!", new[] { "AssignedPersonId", "State" }));}}public override string ToString(){return string.Format("[UpdateTaskInput > TaskId = {0}, AssignedPersonId = {1}, State = {2}]", Id, AssignedPersonId, State);}}其中UpdateTaskInput實(shí)現(xiàn)了ICustomValidate接口,來實(shí)現(xiàn)自定義驗(yàn)證。了解DTO驗(yàn)證可參考 ABP框架 - 驗(yàn)證數(shù)據(jù)傳輸對(duì)象
3.4. 最后來看一下GetTasksInput的定義
其中包括兩個(gè)屬性用來進(jìn)行過濾。
?
public class GetTasksInput{public TaskState? State { get; set; }public int? AssignedPersonId { get; set; }}定義完DTO,是不是腦袋有個(gè)疑問,我在用DTO在展現(xiàn)層與應(yīng)用服務(wù)層進(jìn)行數(shù)據(jù)傳輸,但最終這些DTO都需要轉(zhuǎn)換為實(shí)體才能與數(shù)據(jù)庫直接打交道啊。如果每個(gè)dto都要自己手動(dòng)去轉(zhuǎn)換成對(duì)應(yīng)實(shí)體,這個(gè)工作量也是不可小覷啊。
聰明如你,你肯定會(huì)想肯定有什么方法來減少這個(gè)工作量。
4.使用AutoMapper自動(dòng)映射DTO與實(shí)體
4.1. 簡(jiǎn)要介紹AutoMapper
開始之前,如果對(duì)AutoMapper不是很了解,建議看下這篇文章AutoMapper小結(jié)。
AutoMapper的使用步驟,簡(jiǎn)單總結(jié)下:
- 創(chuàng)建映射規(guī)則(Mapper.CreateMap<source, destination>();)
- 類型映射轉(zhuǎn)換(Mapper.Map<source,destination>(sourceModel))
在Abp中有兩種方式創(chuàng)建映射規(guī)則:
- 特性數(shù)據(jù)注解方式:
- AutoMapFrom、AutoMapTo 特性創(chuàng)建單向映射
- AutoMap 特性創(chuàng)建雙向映射
- 代碼創(chuàng)建映射規(guī)則:
- Mapper.CreateMap<source, destination>();
4.2. 為Task實(shí)體相關(guān)的Dto定義映射規(guī)則
4.2.1.為CreateTasksInput、UpdateTaskInput定義映射規(guī)則
CreateTasksInput、UpdateTaskInput中的屬性名與Task實(shí)體的屬性命名一致,且只需要從Dto映射到實(shí)體,不需要反向映射。所以通過AutoMapTo創(chuàng)建單向映射即可。
?
[AutoMapTo(typeof(Task))] //定義單向映射public class CreateTaskInput{...}[AutoMapTo(typeof(Task))] //定義單向映射public class UpdateTaskInput{...}4.2.2. 為TaskDto定義映射規(guī)則
TaskDto與Task實(shí)體的屬性中,有一個(gè)屬性名不匹配。TaskDto中的AssignedPersonName屬性對(duì)應(yīng)的是Task實(shí)體中的AssignedPerson.FullName屬性。針對(duì)這一屬性映射,AutoMapper沒有這么智能需要我們告訴它怎么做;
?
var taskDtoMapper = mapperConfig.CreateMap<Task, TaskDto>();taskDtoMapper.ForMember(dto => dto.AssignedPersonName, map => map.MapFrom(m => m.AssignedPerson.FullName));為TaskDto與Task創(chuàng)建完自定義映射規(guī)則后,我們需要思考,這段代碼該放在什么地方呢?
5. 創(chuàng)建統(tǒng)一入口注冊(cè)AutoMapper映射規(guī)則
如果在映射規(guī)則既有通過特性方式又有通過代碼方式創(chuàng)建,這時(shí)就會(huì)容易混亂不便維護(hù)。
為了解決這個(gè)問題,統(tǒng)一采用代碼創(chuàng)建映射規(guī)則的方式。并通過IOC容器注冊(cè)所有的映射規(guī)則類,再循環(huán)調(diào)用注冊(cè)方法。
5.1. 定義抽象接口IDtoMapping
應(yīng)用服務(wù)層根目錄創(chuàng)建IDtoMapping接口,定義CreateMapping方法由映射規(guī)則類實(shí)現(xiàn)。
?
namespace LearningMpaAbp {/// <summary>/// 實(shí)現(xiàn)該接口以進(jìn)行映射規(guī)則創(chuàng)建/// </summary>internal interface IDtoMapping{void CreateMapping(IMapperConfigurationExpression mapperConfig);} }5.2. 為Task實(shí)體相關(guān)Dto創(chuàng)建映射類
?
namespace LearningMpaAbp.Tasks {public class TaskDtoMapping : IDtoMapping{public void CreateMapping(IMapperConfigurationExpression mapperConfig){//定義單向映射mapperConfig.CreateMap<CreateTaskInput, Task>();mapperConfig.CreateMap<UpdateTaskInput, Task>();mapperConfig.CreateMap<TaskDto, UpdateTaskInput>();//自定義映射var taskDtoMapper = mapperConfig.CreateMap<Task, TaskDto>();taskDtoMapper.ForMember(dto => dto.AssignedPersonName, map => map.MapFrom(m => m.AssignedPerson.FullName));}} }5.3. 注冊(cè)IDtoMapping依賴
在應(yīng)用服務(wù)的模塊中對(duì)IDtoMapping進(jìn)行依賴注冊(cè),并解析以進(jìn)行映射規(guī)則創(chuàng)建。
?
namespace LearningMpaAbp {[DependsOn(typeof(LearningMpaAbpCoreModule), typeof(AbpAutoMapperModule))]public class LearningMpaAbpApplicationModule : AbpModule{public override void PreInitialize(){Configuration.Modules.AbpAutoMapper().Configurators.Add(mapper =>{//Add your custom AutoMapper mappings here...});}public override void Initialize(){ IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());//注冊(cè)IDtoMappingIocManager.IocContainer.Register(Classes.FromAssembly(Assembly.GetExecutingAssembly()).IncludeNonPublicTypes().BasedOn<IDtoMapping>().WithService.Self().WithService.DefaultInterfaces().LifestyleTransient());//解析依賴,并進(jìn)行映射規(guī)則創(chuàng)建Configuration.Modules.AbpAutoMapper().Configurators.Add(mapper =>{var mappers = IocManager.IocContainer.ResolveAll<IDtoMapping>();foreach (var dtomap in mappers)dtomap.CreateMapping(mapper);});}} }通過這種方式,我們只需要實(shí)現(xiàn)IDtoMappting進(jìn)行映射規(guī)則定義。創(chuàng)建映射規(guī)則的動(dòng)作就交給模塊吧。
6. 萬事俱備,實(shí)現(xiàn)ITaskAppService
認(rèn)真讀完以上內(nèi)容,那么到這一步,就很簡(jiǎn)單了,業(yè)務(wù)只是簡(jiǎn)單的增刪該查,實(shí)現(xiàn)起來就很簡(jiǎn)單了。可以自己嘗試自行實(shí)現(xiàn),再參考代碼:
?
namespace LearningMpaAbp.Tasks {/// <summary>/// Implements <see cref="ITaskAppService"/> to perform task related application functionality./// /// Inherits from <see cref="ApplicationService"/>./// <see cref="ApplicationService"/> contains some basic functionality common for application services (such as logging and localization)./// </summary>public class TaskAppService : LearningMpaAbpAppServiceBase, ITaskAppService{//These members set in constructor using constructor injection.private readonly IRepository<Task> _taskRepository;/// <summary>///In constructor, we can get needed classes/interfaces.///They are sent here by dependency injection system automatically./// </summary>public TaskAppService(IRepository<Task> taskRepository,){_taskRepository = taskRepository;}public GetTasksOutput GetTasks(GetTasksInput input){var query = _taskRepository.GetAll();if (input.AssignedPersonId.HasValue){query = query.Where(t => t.AssignedPersonId == input.AssignedPersonId.Value);}if (input.State.HasValue){query = query.Where(t => t.State == input.State.Value);}//Used AutoMapper to automatically convert List<Task> to List<TaskDto>.return new GetTasksOutput{Tasks = Mapper.Map<List<TaskDto>>(query.ToList())};}public async Task<TaskDto> GetTaskByIdAsync(int taskId){//Called specific GetAllWithPeople method of task repository.var task = await _taskRepository.GetAsync(taskId);//Used AutoMapper to automatically convert List<Task> to List<TaskDto>.return task.MapTo<TaskDto>();}public TaskDto GetTaskById(int taskId){var task = _taskRepository.Get(taskId);return task.MapTo<TaskDto>();}public void UpdateTask(UpdateTaskInput input){//We can use Logger, it's defined in ApplicationService base class.Logger.Info("Updating a task for input: " + input);//Retrieving a task entity with given id using standard Get method of repositories.var task = _taskRepository.Get(input.Id);//Updating changed properties of the retrieved task entity.if (input.State.HasValue){task.State = input.State.Value;}//We even do not call Update method of the repository.//Because an application service method is a 'unit of work' scope as default.//ABP automatically saves all changes when a 'unit of work' scope ends (without any exception).}public int CreateTask(CreateTaskInput input){//We can use Logger, it's defined in ApplicationService class.Logger.Info("Creating a task for input: " + input);//Creating a new Task entity with given input's propertiesvar task = new Task{Description = input.Description,Title = input.Title,State = input.State,CreationTime = Clock.Now};//Saving entity with standard Insert method of repositories.return _taskRepository.InsertAndGetId(task);}public void DeleteTask(int taskId){var task = _taskRepository.Get(taskId);if (task != null){_taskRepository.Delete(task);}}} }到此,此章節(jié)就告一段落。為了加深印象,請(qǐng)自行回答如下問題:
源碼已上傳至Github-LearningMpaAbp,可自行參考。
作者:圣杰
鏈接:https://www.jianshu.com/p/da69ca7b27c6
來源:簡(jiǎn)書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
總結(jié)
以上是生活随笔為你收集整理的ABP入门系列(4)——创建应用服务的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 继伊朗之后,又一个国家加入去美元化浪潮,
- 下一篇: 第十四节: EF的三种模式(四) 之 原