ABP入門系列(4)——建立應用服務
一、解釋下應用服務層
應用服務用於將領域(業務)邏輯暴露給展現層。展現層通過傳入DTO(資料傳輸物件)引數來呼叫應用服務,而應用服務通過領域物件來執行相應的業務邏輯並且將DTO返回給展現層。因此,展現層和領域層將被完全隔離開來。
以下幾點,在建立應用服務時需要注意:
- 在ABP中,一個應用服務需要實現
IApplicationService
介面,最好的實踐是針對每個應用服務都建立相應繼承自IApplicationService
的介面。(通過繼承該介面,ABP會自動幫助依賴注入) - ABP為
IApplicationService
提供了預設的實現ApplicationService
,該基類提供了方便的日誌記錄和本地化功能。實現應用服務的時候繼承自ApplicationService
- ABP中,一個應用服務方法預設是一個工作單元(Unit of Work)。ABP針對UOW模式自動進行資料庫的連線及事務管理,且會自動儲存資料修改。
二、定義ITaskAppService介面
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(); }
觀察方法的引數及返回值,大家可能會發現並未直接使用Task實體物件。這是為什麼呢?因為展現層與應用服務層是通過Data Transfer Object(DTO)進行資料傳輸。
2, 為什麼需要通過dto進行資料傳輸?
總結來說,使用DTO進行資料傳輸具有以下好處。
- 資料隱藏
- 序列化和延遲載入問題
- ABP對DTO提供了約定類以支援驗證
- 引數或返回值改變,通過Dto方便擴充套件
3,Dto規範 (靈活應用)
- ABP建議命名輸入/輸出引數為:MethodNameInput和MethodNameOutput
- 併為每個應用服務方法定義單獨的輸入和輸出DTO(如果為每個方法的輸入輸出都定義一個dto,那將有一個龐大的dto類需要定義維護。一般通過定義一個公用的dto進行共用)
- 即使你的方法只接受/返回一個引數,也最好是建立一個DTO類
- 一般會在對應實體的應用服務資料夾下新建Dtos資料夾來管理Dto類。
三、定義應用服務介面需要用到的DTO
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 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
是一個通用的實體只定義Id屬性的簡單類。直接定義一個TaskDto
的目的是為了在多個應用服務方法中共用。
2, 下面來看看GetTasksOutput的定義
就是直接共用了TaskDto
。
public class GetTasksOutput
{
public List<TaskDto> Tasks { get; set; }
}
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
實現了ICustomValidate
介面,來實現自定義驗證。瞭解DTO驗證可參考 ABP框架 - 驗證資料傳輸物件
##4, 最後來看一下GetTasksInput的定義
其中包括兩個屬性用來進行過濾。
public class GetTasksInput
{
public TaskState? State { get; set; }
public int? AssignedPersonId { get; set; }
}
定義完DTO,是不是腦袋有個疑問,我在用DTO在展現層與應用服務層進行資料傳輸,但最終這些DTO都需要轉換為實體才能與資料庫直接打交道啊。如果每個dto都要自己手動去轉換成對應實體,這個工作量也是不可小覷啊。
聰明如你,你肯定會想肯定有什麼方法來減少這個工作量。
四、使用AutoMapper自動對映DTO與實體
1,簡要介紹AutoMapper
開始之前,如果對AutoMapper不是很瞭解,建議看下這篇文章AutoMapper小結。
AutoMapper的使用步驟,簡單總結下:
- 建立對映規則(
Mapper.CreateMap<source, destination>();
) - 型別對映轉換(
Mapper.Map<source,destination>(sourceModel)
)
在Abp中有兩種方式建立對映規則:
- 特性資料註解方式:
- AutoMapFrom、AutoMapTo 特性建立單向對映
- AutoMap 特性建立雙向對映
- 程式碼建立對映規則:
Mapper.CreateMap<source, destination>();
2,為Task實體相關的Dto定義對映規則
2.1,為CreateTasksInput、UpdateTaskInput定義對映規則
其中CreateTasksInput
、UpdateTaskInput
中的屬性名與Task
實體的屬性命名一致,且只需要從Dto對映到實體,不需要反向對映。所以通過AutoMapTo建立單向對映即可。
[AutoMapTo(typeof(Task))] //定義單向對映
public class CreateTaskInput
{
...
}
[AutoMapTo(typeof(Task))] //定義單向對映
public class UpdateTaskInput
{
...
}
2.2,為TaskDto定義對映規則
TaskDto
與Task
實體的屬性中,有一個屬性名不匹配。TaskDto
中的AssignedPersonName
屬性對應的是Task
實體中的AssignedPerson.FullName
屬性。針對這一屬性對映,AutoMapper沒有這麼智慧需要我們告訴它怎麼做;
var taskDtoMapper = mapperConfig.CreateMap<Task, TaskDto>();
taskDtoMapper.ForMember(dto => dto.AssignedPersonName, map => map.MapFrom(m => m.AssignedPerson.FullName));
為TaskDto
與Task
建立完自定義對映規則後,我們需要思考,這段程式碼該放在什麼地方呢?
四、建立統一入口註冊AutoMapper對映規則
如果在對映規則既有通過特性方式又有通過程式碼方式建立,這時就會容易混亂不便維護。
為了解決這個問題,統一採用程式碼建立對映規則的方式。並通過IOC容器註冊所有的對映規則類,再迴圈呼叫註冊方法。
1,定義抽象介面IDtoMapping
應用服務層根目錄建立IDtoMapping
介面,定義CreateMapping
方法由對映規則類實現。
namespace LearningMpaAbp
{
/// <summary>
/// 實現該介面以進行對映規則建立
/// </summary>
internal interface IDtoMapping
{
void CreateMapping(IMapperConfigurationExpression mapperConfig);
}
}
2,為Task實體相關Dto建立對映類
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));
}
}
}
3,註冊IDtoMapping依賴
在應用服務的模組中對IDtoMapping
進行依賴註冊,並解析以進行對映規則建立。
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());
//註冊IDtoMapping
IocManager.IocContainer.Register(
Classes.FromAssembly(Assembly.GetExecutingAssembly())
.IncludeNonPublicTypes()
.BasedOn<IDtoMapping>()
.WithService.Self()
.WithService.DefaultInterfaces()
.LifestyleTransient()
);
//解析依賴,並進行對映規則建立
Configuration.Modules.AbpAutoMapper().Configurators.Add(mapper =>
{
var mappers = IocManager.IocContainer.ResolveAll<IDtoMapping>();
foreach (var dtomap in mappers)
dtomap.CreateMapping(mapper);
});
}
}
}
通過這種方式,我們只需要實現IDtoMappting
進行對映規則定義。建立對映規則的動作就交給模組吧。
五、萬事俱備,實現ITaskAppService
認真讀完以上內容,那麼到這一步,就很簡單了,業務只是簡單的增刪該查,實現起來就很簡單了。可以自己嘗試自行實現,再參考程式碼:
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;
private readonly IRepository<Person> _personRepository;
/// <summary>
///In constructor, we can get needed classes/interfaces.
///They are sent here by dependency injection system automatically.
/// </summary>
public TaskAppService(IRepository<Task> taskRepository, IRepository<Person> personRepository)
{
_taskRepository = taskRepository;
_personRepository = personRepository;
}
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;
}
if (input.AssignedPersonId.HasValue)
{
task.AssignedPerson = _personRepository.Load(input.AssignedPersonId.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
};
if (input.AssignedPersonId.HasValue)
{
task.AssignedPerson = _personRepository.Load(input.AssignedPersonId.Value);
}
//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);
}
}
}
}
到此,此章節就告一段落。為了加深印象,請自行回答如下問題:
- 什麼是應用服務層?
- 如何定義應用服務介面?
- 什麼DTO,如何定義DTO?
- DTO如何與實體進行自動對映?
- 如何對對映規則統一建立?
相關推薦
ABP入門系列(4)——建立應用服務
一、解釋下應用服務層 應用服務用於將領域(業務)邏輯暴露給展現層。展現層通過傳入DTO(資料傳輸物件)引數來呼叫應用服務,而應用服務通過領域物件來執行相應的業務邏輯並且將DTO返回給展現層。因此,展現層和領域層將被完全隔離開來。 以下幾點,在建立應用服務時需要注意: 在ABP中,一個應用服務需要實現IAp
ABP入門系列(15)——建立微信公眾號模組
1. 引言 現在的網際網路已不在僅僅侷限於網頁應用,IOS、Android、平板、智慧家居等平臺正如火如荼的迅速發展,移動應用的需求也空前旺盛。所有的網際網路公司都不想錯過這一次移動浪潮,佈局移動市場分一份移動紅利。 的確,智慧手機作為我們日常生活已必不可少的一部分,通過手機app能夠獲得更好的體驗,比如
ABP入門系列(18)—— 使用領域服務
1.引言 自上次更新有一個多月了,發現越往下寫,越不知如何去寫。特別是當遇到DDD中一些概念術語的時候,尤其迷惑。如果只是簡單的去介紹如何去使用ABP,我只需參照官方文件,實現到任務清單Demo中去就可以了,不勞神不費力。但是,這樣就等於一知半解。 知之為知之,不知為不知,是知也。知其然知其所以然,方能舉
ABP入門系列(14)——應用BootstrapTable表格外掛
1. 引言 之前的文章ABP入門系列(7)——分頁實現講解了如何進行分頁展示,但其分頁展示僅適用於前臺web分頁,在後臺管理系統中並不適用。後臺管理系統中的資料展示一般都是使用一些表格外掛來完成的。這一節我們就使用BootstrapTable進行舉例說明。 2. BootstrapTable 基於 B
ABP入門系列(2)——領域層建立實體
這一節我們主要和領域層打交道。首先我們要對ABP的體系結構以及從模板建立的解決方案進行一一對應。網上有程式碼生成器去簡化我們這一步的任務,但是不建議初學者去使用。 一、首先來看看ABP體系結構 領域層就是業務層,是一個專案的核心,所有業務規則都應該在領域層實現。 實體(Entity): 實體代表業務領域的
ABP入門系列(1)——通過模板建立MAP版本專案
一、從官網建立模板專案 依次按下圖選擇: 輸入驗證碼開始下載 下載提示: 二、啟動專案 使用VS2015開啟專案,還原Nuget包: 設定以Web結尾的專案,設定為啟動專案: 開啟Web.config,修改連線字串。(因為我本地裝的sqlserver是例項是.sqlexpress,所以需要
backbone入門系列(4)集合
src 單獨 -1 lec 指定 one js代碼 bsp 技術 collection就是一堆model的集合,這個集合就是個舞臺,可以放一個人說單口相聲,也可以對口,也可以群口,,, 在前文,也就是入門系列3的基礎上,添加js代碼 var noteCollection=B
arcgis jsapi介面入門系列(4):用程式碼在地圖畫點線面
PS:用程式碼畫點這樣寫是為了跟後面的用滑鼠畫點線面區分出來 畫點 drawPointGraphic: function () { //點有多種樣式:一般的點,顯示文字,顯示圖片 //一般的點
ABP入門系列(12)——如何升級Abp並除錯原始碼
1. 升級Abp 本系列教程是基於Abp V1.0版本,現在Abp版本已經升級至V1.4.2(截至至文章釋出時間),其中新增了New Feature,並對Abp做了相應的Enhancements,以及Bug fixs。現在我們就把它升級至最新版本,那如何升級呢? 下面就請按我的步驟來將Abp由V1.0升級
ABP入門系列(16)——通過webapi與系統進行互動
1. 引言 上一節我們講解了如何建立微信公眾號模組,這一節我們就繼續跟進,來講一講公眾號模組如何與系統進行互動。 微信公眾號模組作為一個獨立的web模組部署,要想與現有的【任務清單】進行互動,我們要想明白以下幾個問題: 如何進行互動? ABP模板專案中預設建立了webapi專案,其動態webapi技術允
ABP入門系列(6)——定義導航選單
完成了增刪改查以及頁面展示,這一節我們來為任務清單新增【導航選單】。 在以往的專案中,大家可能會手動在layout頁面中新增一個a標籤來新增導航選單,這也是一種方式,但是如果要針對不同使用者不同許可權決定是否顯示某個選單,那麼直接在layout頁面中去控制就不方便了。 不過,ABP已經為大家考慮了這一點,集
ABP入門系列(8)——Json格式化
講完了分頁功能,這一節我們先不急著實現新的功能。來簡要介紹下Abp中Json的用法。為什麼要在這一節講呢?當然是做鋪墊啊,後面的系列文章會經常和Json這個東西打交道。 一、Json是幹什麼的 JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。 易於人閱讀和編寫
ABP入門系列(19)——使用領域事件
1.引言 最近剛學習了下DDD中領域事件的理論知識,總的來說領域事件主要有兩個作用,一是解耦,二是使用領域事件進行事務的拆分,通過引入事件儲存,來實現資料的最終一致性。若想了解DDD中領域事件的概念,可參考DDD理論學習系列(9)-- 領域事件。 Abp中使用事件匯流排來實現領域事件,而關於事件匯流排的
ABP入門系列(9)——許可權管理
完成了簡單的增刪改查和分頁功能,是不是覺得少了點什麼? 是的,少了許可權管理。既然涉及到了許可權,那我們就細化下任務清單的功能點: 登入的使用者才能檢視任務清單 使用者可以無限建立任務並分配給自己,但只能對自己建立的任務進行查詢、修改 管理員可以建立任務並分配給他人 管理員具有刪除任務的許可權 從以上
ABP入門系列(5)——展現層實現增刪改查
這一章節將通過完善Controller、View、ViewModel,來實現展現層的增刪改查。最終實現效果如下圖: 一、定義Controller ABP對ASP.NET MVC Controllers進行了整合,通過引入Abp.Web.Mvc名稱空間,建立Controller繼承自AbpControlle
ABP入門系列(11)——編寫單元測試
1. 前言 In computer programming, unit testing is a software testing method by which individual units of source code, sets of one or more computer program
ABP入門系列(3)——領域層定義倉儲並實現
一、先來介紹下倉儲 倉儲(Repository): 倉儲用來操作資料庫進行資料存取。倉儲介面在領域層定義,而倉儲的實現類應該寫在基礎設施層。 在ABP中,倉儲類要實現IRepository介面,介面定義了常用的增刪改查以及聚合方法,其中包括同步及非同步方法。主要包括以下方法: ABP針對不同的ORM框架對
ABP入門系列(13)——Redis快取用起來
1. 引言 建立任務時我們需要指定分配給誰,Demo中我們使用一個下拉列表用來顯示當前系統的所有使用者,以供使用者選擇。我們每建立一個任務時都要去資料庫取一次使用者列表,然後繫結到使用者下拉列表顯示。如果就單單對一個demo來說,這樣實現也無可厚非,但是在正式專案中,顯然是不合理的,浪費程式效能,有待優化
ABP入門系列(7)——分頁實現
完成了任務清單的增刪改查,咱們來講一講必不可少的的分頁功能。 首先很慶幸ABP已經幫我們封裝了分頁實現,實在是貼心啊。 來來來,這一節咱們就來捋一捋如何使用ABP的進行分頁吧。 一、分頁請求DTO定義 資料傳輸物件(Data Transfer Objects)用於應用層和展現層的資料傳輸。 展現層傳入資料
ABP入門系列(17)——使用ABP整合的郵件系統傳送郵件
ABP中對郵件的封裝主要整合在Abp.Net.Mail和Abp.Net.Mail.Smtp名稱空間下,相應原始碼在此。 #一、Abp整合的郵件模組是如何實現的 分析可以看出主要由以下幾個核心類組成: EmailSettingNames:靜態常量類,主要定義了傳送郵件需要的相關引數:Port、Host、Us