ABP入門系列(5)-創建應用服務

黄舟
發布: 2017-01-16 17:31:09
原創
2631 人瀏覽過

一、解釋下應用服務層

應用服務用於將領域(業務)邏輯暴露給展現層。展現層透過傳入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方便擴充

了解更多詳情請參考:
ABP框架傳輸物件

3,Dto規格(靈活應用)

ABP建議命名輸入/輸出參數為:MethodNameInput和MethodNameOutput

並為每個應用服務方法定義單獨的輸入和輸出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&#39;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();)

类型映射转换(Mapper.Map(sourceModel))

在Abp中有两种方式创建映射规则:

特性数据注解方式:

AutoMapFrom、AutoMapTo 特性创建单向映射

AutoMap 特性创建双向映射

代码创建映射规则:

Mapper.CreateMap();

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();
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&#39;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 &#39;unit of work&#39; scope as default.
            //ABP automatically saves all changes when a &#39;unit of work&#39; scope ends (without any exception).
        }

        public int CreateTask(CreateTaskInput input)
        {            //We can use Logger, it&#39;s defined in ApplicationService class.
            Logger.Info("Creating a task for input: " + input);            //Creating a new Task entity with given input&#39;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入門系列(5)-創建應用服務的內容,更多相關內容請關注PHP中文網(www.php.cn)!


相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!