1. 解釋下應(yīng)用服務(wù)層
應(yīng)用服務(wù)用于將領(lǐng)域(業(yè)務(wù))邏輯暴露給展現(xiàn)層劈愚。展現(xiàn)層通過(guò)傳入DTO(數(shù)據(jù)傳輸對(duì)象)參數(shù)來(lái)調(diào)用應(yīng)用服務(wù),而應(yīng)用服務(wù)通過(guò)領(lǐng)域?qū)ο髞?lái)執(zhí)行相應(yīng)的業(yè)務(wù)邏輯并且將DTO返回給展現(xiàn)層闻妓。因此菌羽,展現(xiàn)層和領(lǐng)域?qū)訉⒈煌耆綦x開來(lái)。
以下幾點(diǎn)由缆,在創(chuàng)建應(yīng)用服務(wù)時(shí)需要注意:
- 在ABP中注祖,一個(gè)應(yīng)用服務(wù)需要實(shí)現(xiàn)
IApplicationService
接口,最好的實(shí)踐是針對(duì)每個(gè)應(yīng)用服務(wù)都創(chuàng)建相應(yīng)繼承自IApplicationService
的接口均唉。(通過(guò)繼承該接口是晨,ABP會(huì)自動(dòng)幫助依賴注入) - ABP為
IApplicationService
提供了默認(rèn)的實(shí)現(xiàn)ApplicationService
,該基類提供了方便的日志記錄和本地化功能舔箭。實(shí)現(xiàn)應(yīng)用服務(wù)的時(shí)候繼承自ApplicationService
并實(shí)現(xiàn)定義的接口即可罩缴。 - ABP中,一個(gè)應(yīng)用服務(wù)方法默認(rèn)是一個(gè)工作單元(Unit of Work)层扶。ABP針對(duì)UOW模式自動(dòng)進(jìn)行數(shù)據(jù)庫(kù)的連接及事務(wù)管理箫章,且會(huì)自動(dòng)保存數(shù)據(jù)修改。
2. 定義ITaskAppService接口
2.1. 先來(lái)看看定義的接口
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ù)層是通過(guò)Data Transfer Object(DTO)進(jìn)行數(shù)據(jù)傳輸稚叹。
2.2. 為什么需要通過(guò)dto進(jìn)行數(shù)據(jù)傳輸焰薄?
總結(jié)來(lái)說(shuō),使用DTO進(jìn)行數(shù)據(jù)傳輸具有以下好處扒袖。
- 數(shù)據(jù)隱藏
- 序列化和延遲加載問(wèn)題
- ABP對(duì)DTO提供了約定類以支持驗(yàn)證
- 參數(shù)或返回值改變塞茅,通過(guò)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ù)季率。一般通過(guò)定義一個(gè)公用的dto進(jìn)行共用)
- 即使你的方法只接受/返回一個(gè)參數(shù)野瘦,也最好是創(chuàng)建一個(gè)DTO類
- 一般會(huì)在對(duì)應(yīng)實(shí)體的應(yīng)用服務(wù)文件夾下新建Dtos文件夾來(lái)管理Dto類。
3. 定義應(yīng)用服務(wù)接口需要用到的DTO
3.1. 先來(lái)看看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 tasks
public 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. 下面來(lái)看看GetTasksOutput的定義
就是直接共用了TaskDto
泞遗。
public class GetTasksOutput
{
public List<TaskDto> Tasks { get; set; }
}
3.3. 再來(lái)看看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
接口,來(lái)實(shí)現(xiàn)自定義驗(yàn)證史辙。了解DTO驗(yàn)證可參考 ABP框架 - 驗(yàn)證數(shù)據(jù)傳輸對(duì)象
3.4. 最后來(lái)看一下GetTasksInput的定義
其中包括兩個(gè)屬性用來(lái)進(jìn)行過(guò)濾汹买。
public class GetTasksInput
{
public TaskState? State { get; set; }
public int? AssignedPersonId { get; set; }
}
定義完DTO佩伤,是不是腦袋有個(gè)疑問(wèn),我在用DTO在展現(xiàn)層與應(yīng)用服務(wù)層進(jìn)行數(shù)據(jù)傳輸晦毙,但最終這些DTO都需要轉(zhuǎn)換為實(shí)體才能與數(shù)據(jù)庫(kù)直接打交道啊生巡。如果每個(gè)dto都要自己手動(dòng)去轉(zhuǎn)換成對(duì)應(yīng)實(shí)體,這個(gè)工作量也是不可小覷啊见妒。
聰明如你孤荣,你肯定會(huì)想肯定有什么方法來(lái)減少這個(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í)體秸谢,不需要反向映射凛澎。所以通過(guò)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沒(méi)有這么智能需要我們告訴它怎么做最铁;
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ī)則既有通過(guò)特性方式又有通過(guò)代碼方式創(chuàng)建,這時(shí)就會(huì)容易混亂不便維護(hù)系枪。
為了解決這個(gè)問(wèn)題雀哨,統(tǒng)一采用代碼創(chuàng)建映射規(guī)則的方式。并通過(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è)IDtoMapping
IocManager.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);
});
}
}
}
通過(guò)這種方式尸饺,我們只需要實(shí)現(xiàn)IDtoMappting
進(jìn)行映射規(guī)則定義进统。創(chuàng)建映射規(guī)則的動(dòng)作就交給模塊吧。
6. 萬(wàn)事俱備侵佃,實(shí)現(xiàn)ITaskAppService
認(rèn)真讀完以上內(nèi)容麻昼,那么到這一步,就很簡(jiǎn)單了馋辈,業(yè)務(wù)只是簡(jiǎn)單的增刪該查抚芦,實(shí)現(xiàn)起來(lái)就很簡(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 properties
var 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)自行回答如下問(wèn)題:
- 什么是應(yīng)用服務(wù)層?
- 如何定義應(yīng)用服務(wù)接口洗搂?
- 什么DTO消返,如何定義DTO?
- DTO如何與實(shí)體進(jìn)行自動(dòng)映射耘拇?
- 如何對(duì)映射規(guī)則統(tǒng)一創(chuàng)建撵颊?
源碼已上傳至Github-LearningMpaAbp,可自行參考惫叛。