ASP.NET ZERO 學習 —— (11) 應用開發Demo之創建應用服務

創建Person的應用服務

應用服務是用來被客戶端(表現層)調用執行邏輯操作。

應用服務是放在.Application項目中。我們創建第一應用服務用來從服務端獲取Person信息。
首先在Application項目中創建一個叫Person的文件夾,再在Person文件夾下創建一個叫Dto的文件夾。

這裏寫圖片描述

創建一個接口來定義Person應用服務:

    public interface IPersonAppService: IApplicationService
    {
        ListResultDto<PersonListDto> GetPeople(GetPeopleInput input);
    }

應用服務是用來獲取或返回DTO對象,ListResultDto是框架創建用來返回DTO對象列表的幫助類。GetPeopleInput是GetPeople方法的請求參數。所以,GetPeopleInput和PersonListDto 定義如下:

    public class GetPeopleInput
    {
        public string Filter { get; set; }
    }
    [AutoMapFrom(typeof(Entities.Person))]
    public class PersonListDto : FullAuditedEntityDto
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public string EmailAddress { get; set; }
    }

AutoMapFrom屬性是使用AutoMapper創建PersonPersonListDto的映射。FullAuditedEntityDto包含了審計屬性。參見應用服務DTO文檔瞭解更多。

當定義完接口後,我們如下面所示來進行實現:

    public class PersonAppService : AbpZeroTemplateAppServiceBase, IPersonAppService
    {
        private readonly IRepository<Entities.Person> _personRepository;

        public PersonAppService(IRepository<Entities.Person> personRepository)
        {
            this._personRepository = personRepository;
        }
        public ListResultDto<PersonListDto> GetPeople(GetPeopleInput input)
        {
            var persons = this._personRepository
                .GetAll()
                .WhereIf(
                    !input.Filter.IsNullOrEmpty(),
                    p => p.Name.Contains(input.Filter) ||
                        p.Surname.Contains(input.Filter) ||
                        p.EmailAddress.Contains(input.Filter)
                )
                .OrderBy(p => p.Name)
                .ThenBy(p => p.Surname)
                .ToList();

            return new ListResultDto<PersonListDto>(persons.MapTo<List<PersonListDto>>());
        }
    }

我們注入Person Repository並使用它從數據庫過濾並獲取Person的信息。

WhereIf是一個擴展方法(在Abp.Linq.Extensions命名空間中定義)。只用當Filter不爲Null或Empty,它才執行Where條件語句。
IsNullOrEmpty也是一個擴展方法(在Abp.Extensions命名空間中定義)。ABP擁有許多類似的快捷擴展方法。
MapTo方法通過使用AutoMapper自動將 Person 對象列表轉換爲 PersonListDto 對象列表

連接與事務管理

我們不用手動打開數據庫連接或開啓/提交事務。在ABP框架的工作單元(Unit Of Work)系統中已進行了自動處理。見UOW瞭解更多。

錯誤捕獲

我們不用手動捕獲錯誤(使用Try-Catch),因爲ABP框架會自動在Web層捕獲所有錯誤並返回適當的錯誤消息至客戶端。然後在客戶端捕獲錯誤並向用戶顯示所需的錯誤信息。見錯誤捕獲瞭解更多。

發佈了98 篇原創文章 · 獲贊 54 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章