ABP入門系列(4)——創建應用服務


ABP入門系列目錄——學習Abp框架之實操演練

一、解釋下應用服務層

應用服務用於將領域(業務)邏輯暴露給展現層。展現層通過傳入DTO(數據傳輸對象)參數來調用應用服務,而應用服務通過領域對象來執行相應的業務邏輯並且將DTO返回給展現層。因此,展現層和領域層將被完全隔離開來。
以下幾點,在創建應用服務時需要注意:

  1. 在ABP中,一個應用服務需要實現IApplicationService接口,最好的實踐是針對每個應用服務都創建相應繼承自IApplicationService的接口。(通過繼承該接口,ABP會自動幫助依賴注入)
  2. ABP為IApplicationService提供了默認的實現ApplicationService,該基類提供了方便的日志記錄和本地化功能。實現應用服務的時候繼承自ApplicationService並實現定義的接口即可。
  3. 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類需要定義維護。一般通過定義一個公用的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直接繼承自EntityDtoEntityDto是一個通用的實體只定義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定義映射規則

其中CreateTasksInputUpdateTaskInput中的屬性名與Task實體的屬性命名一致,且只需要從Dto映射到實體,不需要反向映射。所以通過AutoMapTo創建單向映射即可。

    [AutoMapTo(typeof(Task))] //定義單向映射
    public class CreateTaskInput
    {
      ...
    }

     [AutoMapTo(typeof(Task))] //定義單向映射
    public class UpdateTaskInput
    {
      ...
    }

2.2,為TaskDto定義映射規則

TaskDtoTask實體的屬性中,有一個屬性名不匹配。TaskDto中的AssignedPersonName屬性對應的是Task實體中的AssignedPerson.FullName屬性。針對這一屬性映射,AutoMapper沒有這么智能需要我們告訴它怎么做;

 var taskDtoMapper = mapperConfig.CreateMap<Task, TaskDto>();
 taskDtoMapper.ForMember(dto => dto.AssignedPersonName, map => map.MapFrom(m => m.AssignedPerson.FullName));

TaskDtoTask創建完自定義映射規則后,我們需要思考,這段代碼該放在什么地方呢?

四、創建統一入口注冊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);
            }
        }
    }
}

到此,此章節就告一段落。為了加深印象,請自行回答如下問題:

  1. 什么是應用服務層?
  2. 如何定義應用服務接口?
  3. 什么DTO,如何定義DTO?
  4. DTO如何與實體進行自動映射?
  5. 如何對映射規則統一創建?

源碼已上傳至Github-LearningMpaAbp,可自行參考。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM