• ABP创建应用服务


    原文作者:圣杰

    原文地址:ABP入门系列(4)——创建应用服务

    在原文作者上进行改正,适配ABP新版本。内容相同

    1. 解释下应用服务层

    应用服务用于将领域(业务)逻辑暴露给展现层。展现层通过传入DTO(数据传输对象)参数来调用应用服务,而应用服务通过领域对象来执行相应的业务逻辑并且将DTO返回给展现层。因此,展现层和领域层将被完全隔离开来。
    以下几点,在创建应用服务时需要注意:

    1. 在ABP中,一个应用服务需要实现IApplicationService接口,最好的实践是针对每个应用服务都创建相应继承自IApplicationService的接口。(通过继承该接口,ABP会自动帮助依赖注入)
    2. ABP为IApplicationService提供了默认的实现ApplicationService,该基类提供了方便的日志记录和本地化功能。实现应用服务的时候继承自ApplicationService并实现定义的接口即可。
    3. ABP中,一个应用服务方法默认是一个工作单元(Unit of Work)。ABP针对UOW模式自动进行数据库的连接及事务管理,且会自动保存数据修改。

    2. 定义ITaskAppService接口

    2.1. 先来看看定义的接口

      将服务接口声明在xxxx.Application =》 Tasks =》Services目录下

     1 using Abp.Application.Services;
     2 using Coreqi.Tasks.Dtos;
     3 using System;
     4 using System.Collections.Generic;
     5 using System.Text;
     6 using System.Threading.Tasks;
     7 
     8 namespace Coreqi.Tasks.Services
     9 {
    10     public interface ITaskAppServic:IApplicationService
    11     {
    12         GetTasksOutput GetTasks(GetTasksInput input);
    13 
    14         void UpdateTask(UpdateTaskInput input);
    15 
    16         int CreateTask(CreateTaskInput input);
    17 
    18         Task<TaskDto> GetTaskByIdAsync(int taskId);
    19 
    20         TaskDto GetTaskById(int taskId);
    21 
    22         void DeleteTask(int taskId);
    23 
    24         IList<TaskDto> GetAllTasks();
    25     }
    26 }

    观察方法的参数及返回值,大家可能会发现并未直接使用Task实体对象。这是为什么呢?因为展现层与应用服务层是通过Data Transfer Object(DTO)进行数据传输。

    2.2. 为什么需要通过dto进行数据传输?

    总结来说,使用DTO进行数据传输具有以下好处。

    • 数据隐藏
    • 序列化和延迟加载问题
    • ABP对DTO提供了约定类以支持验证
    • 参数或返回值改变,通过Dto方便扩展

    了解更多详情请参考:
    ABP框架 - 数据传输对象

    2.3. Dto规范 (灵活应用)

    • ABP建议命名输入/输出参数为:MethodNameInput和MethodNameOutput
    • 并为每个应用服务方法定义单独的输入和输出DTO(如果为每个方法的输入输出都定义一个dto,那将有一个庞大的dto类需要定义维护。一般通过定义一个公用的dto进行共用)
    • 即使你的方法只接受/返回一个参数,也最好是创建一个DTO类
    • 一般会在对应实体的应用服务文件夹下新建Dtos文件夹来管理Dto类。

    3. 定义应用服务接口需要用到的DTO

    3.1. 先来看看TaskDto的定义

     1 using Abp.Application.Services.Dto;
     2 using System;
     3 using System.Collections.Generic;
     4 using System.Text;
     5 
     6 namespace Coreqi.Tasks.Dtos
     7 {
     8     public class TaskDto: EntityDto
     9     {
    10         public long? AssignedPersonId { get; set; }
    11 
    12         public string AssignedPersonName { get; set; }
    13 
    14         public string Title { get; set; }
    15 
    16         public string Description { get; set; }
    17 
    18         public DateTime CreationTime { get; set; }
    19 
    20         public TaskState State { get; set; }
    21 
    22         public override string ToString()
    23         {
    24             return string.Format(
    25                 "[Task Id={0}, Description={1}, CreationTime={2}, AssignedPersonName={3}, State={4}]",
    26                 Id,
    27                 Description,
    28                 CreationTime,
    29                 AssignedPersonId,
    30                 (TaskState)State
    31                 );
    32         }
    33     }
    34 }

    TaskDto直接继承自EntityDtoEntityDto是一个通用的实体只定义Id属性的简单类。直接定义一个TaskDto的目的是为了在多个应用服务方法中共用。

    3.2. 下面来看看GetTasksOutput的定义

    就是直接共用了TaskDto

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Coreqi.Tasks.Dtos
     6 {
     7     public class GetTasksOutput
     8     {
     9         public List<TaskDto> Tasks { get; set; }
    10     }
    11 }

    3.3. 再来看看CreateTaskInput、UpdateTaskInput

     1 using System;
     2 using System.Collections.Generic;
     3 using System.ComponentModel.DataAnnotations;
     4 using System.Text;
     5 
     6 namespace Coreqi.Tasks.Dtos
     7 {
     8     public class CreateTaskInput
     9     {
    10         public int? AssignedPersonId { get; set; }
    11 
    12         [Required]
    13         public string Description { get; set; }
    14 
    15         [Required]
    16         public string Title { get; set; }
    17 
    18         public TaskState State { get; set; }
    19         public override string ToString()
    20         {
    21             return string.Format("[CreateTaskInput > AssignedPersonId = {0}, Description = {1}]", AssignedPersonId, Description);
    22         }
    23     }
    24 }
     1 using Abp.Runtime.Validation;
     2 using System;
     3 using System.Collections.Generic;
     4 using System.ComponentModel.DataAnnotations;
     5 using System.Text;
     6 
     7 namespace Coreqi.Tasks.Dtos
     8 {
     9     public class UpdateTaskInput: ICustomValidate
    10     {
    11         [Range(1, Int32.MaxValue)] //Data annotation attributes work as expected.
    12         public int Id { get; set; }
    13 
    14         public int? AssignedPersonId { get; set; }
    15 
    16         public TaskState? State { get; set; }
    17 
    18         [Required]
    19         public string Title { get; set; }
    20 
    21         [Required]
    22         public string Description { get; set; }
    23 
    24         //Custom validation method. It's called by ABP after data annotation validations.
    25         public void AddValidationErrors(CustomValidationContext context)
    26         {
    27             if (AssignedPersonId == null && State == null)
    28             {
    29                 context.Results.Add(new ValidationResult("Both of AssignedPersonId and State can not be null in order to update a Task!", new[] { "AssignedPersonId", "State" }));
    30             }
    31         }
    32 
    33         public override string ToString()
    34         {
    35             return string.Format("[UpdateTaskInput > TaskId = {0}, AssignedPersonId = {1}, State = {2}]", Id, AssignedPersonId, State);
    36         }
    37     }
    38 }

    其中UpdateTaskInput实现了ICustomValidate接口,来实现自定义验证。了解DTO验证可参考 ABP框架 - 验证数据传输对象

    3.4. 最后来看一下GetTasksInput的定义

    其中包括两个属性用来进行过滤。

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace Coreqi.Tasks.Dtos
     6 {
     7     public class GetTasksInput
     8     {
     9         public TaskState? State { get; set; }
    10 
    11         public int? AssignedPersonId { get; set; }
    12     }
    13 }

    定义完DTO,是不是脑袋有个疑问,我在用DTO在展现层与应用服务层进行数据传输,但最终这些DTO都需要转换为实体才能与数据库直接打交道啊。如果每个dto都要自己手动去转换成对应实体,这个工作量也是不可小觑啊。
    聪明如你,你肯定会想肯定有什么方法来减少这个工作量。

    4.使用AutoMapper自动映射DTO与实体

    4.1. 简要介绍AutoMapper

    开始之前,如果对AutoMapper不是很了解,建议看下这篇文章AutoMapper小结

    AutoMapper的使用步骤,简单总结下:

    • 创建映射规则(Mapper.CreateMap<source, destination>();
    • 类型映射转换(Mapper.Map<source,destination>(sourceModel)

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

    • 特性数据注解方式:
      • AutoMapFrom、AutoMapTo 特性创建单向映射
      • AutoMap 特性创建双向映射
    • 代码创建映射规则:
      • Mapper.CreateMap<source, destination>();

    4.2. 为Task实体相关的Dto定义映射规则

    4.2.1.为CreateTasksInput、UpdateTaskInput定义映射规则

    CreateTasksInputUpdateTaskInput中的属性名与Task实体的属性命名一致,且只需要从Dto映射到实体,不需要反向映射。所以通过AutoMapTo创建单向映射即可。

     1     [AutoMapTo(typeof(Task))] //定义单向映射
     2     public class CreateTaskInput
     3     {
     4       ...
     5     }
     6 
     7     [AutoMapTo(typeof(Task))] //定义单向映射
     8     public class UpdateTaskInput
     9     {
    10       ...
    11     }

    4.2.2. 为TaskDto定义映射规则

    TaskDtoTask实体的属性中,有一个属性名不匹配。TaskDto中的AssignedPersonName属性对应的是Task实体中的AssignedPerson.FullName属性。针对这一属性映射,AutoMapper没有这么智能需要我们告诉它怎么做;

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

    TaskDtoTask创建完自定义映射规则后,我们需要思考,这段代码该放在什么地方呢?

    5. 创建统一入口注册AutoMapper映射规则

    如果在映射规则既有通过特性方式又有通过代码方式创建,这时就会容易混乱不便维护。
    为了解决这个问题,统一采用代码创建映射规则的方式。并通过IOC容器注册所有的映射规则类,再循环调用注册方法。

    5.1. 定义抽象接口IDtoMapping

    应用服务层根目录(xxxx.Application)创建IDtoMapping接口,定义CreateMapping方法由映射规则类实现。

     1 using AutoMapper;
     2 using System;
     3 using System.Collections.Generic;
     4 using System.Text;
     5 
     6 namespace Coreqi
     7 {
     8     /// <summary>
     9     /// 实现该接口以进行映射规则创建
    10     /// </summary>
    11     public interface IDtoMapping
    12     {
    13         void CreateMapping(IMapperConfigurationExpression mapperConfig);
    14     }
    15 }

    5.2. 为Task实体相关Dto创建映射类

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 using AutoMapper;
     5 using Coreqi.Tasks;
     6 using Coreqi.Tasks.Dtos;
     7 
     8 namespace Coreqi
     9 {
    10     public class TaskDtoMapping : IDtoMapping
    11     {
    12         public void CreateMapping(IMapperConfigurationExpression mapperConfig)
    13         {
    14             //定义单向映射
    15             mapperConfig.CreateMap<CreateTaskInput, Task>();
    16             mapperConfig.CreateMap<UpdateTaskInput, Task>();
    17             mapperConfig.CreateMap<TaskDto, UpdateTaskInput>();
    18 
    19             //自定义映射
    20             var taskDtoMapper = mapperConfig.CreateMap<Task, TaskDto>();
    21             taskDtoMapper.ForMember(dto => dto.AssignedPersonName, map => map.MapFrom(m => m.AssignedPerson.FullName));
    22         }
    23     }
    24 }

    5.3. 注册IDtoMapping依赖

    在应用服务的模块中对IDtoMapping进行依赖注册,并解析以进行映射规则创建。

     1 namespace LearningMpaAbp
     2 {
     3     [DependsOn(typeof(LearningMpaAbpCoreModule), typeof(AbpAutoMapperModule))]
     4     public class LearningMpaAbpApplicationModule : AbpModule
     5     {
     6         public override void PreInitialize()
     7         {
     8             Configuration.Modules.AbpAutoMapper().Configurators.Add(mapper =>
     9             {
    10                 //Add your custom AutoMapper mappings here...
    11             });
    12         }
    13 
    14         public override void Initialize()
    15         {           
    16            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
    17 
    18             //注册IDtoMapping
    19             IocManager.IocContainer.Register(
    20                 Classes.FromAssembly(Assembly.GetExecutingAssembly())
    21                     .IncludeNonPublicTypes()
    22                     .BasedOn<IDtoMapping>()
    23                     .WithService.Self()
    24                     .WithService.DefaultInterfaces()
    25                     .LifestyleTransient()
    26             );
    27 
    28             //解析依赖,并进行映射规则创建
    29             Configuration.Modules.AbpAutoMapper().Configurators.Add(mapper =>
    30             {
    31                 var mappers = IocManager.IocContainer.ResolveAll<IDtoMapping>();
    32                 foreach (var dtomap in mappers)
    33                     dtomap.CreateMapping(mapper);
    34             });
    35         }
    36     }
    37 }

    通过这种方式,我们只需要实现IDtoMappting进行映射规则定义。创建映射规则的动作就交给模块吧。

    6. 万事俱备,实现ITaskAppService

    认真读完以上内容,那么到这一步,就很简单了,业务只是简单的增删该查,实现起来就很简单了。可以自己尝试自行实现,再参考代码:

      1 namespace LearningMpaAbp.Tasks
      2 {
      3     /// <summary>
      4     /// Implements <see cref="ITaskAppService"/> to perform task related application functionality.
      5     /// 
      6     /// Inherits from <see cref="ApplicationService"/>.
      7     /// <see cref="ApplicationService"/> contains some basic functionality common for application services (such as logging and localization).
      8     /// </summary>
      9     public class TaskAppService : LearningMpaAbpAppServiceBase, ITaskAppService
     10     {
     11         //These members set in constructor using constructor injection.
     12 
     13         private readonly IRepository<Task> _taskRepository;
     14 
     15         /// <summary>
     16         ///In constructor, we can get needed classes/interfaces.
     17         ///They are sent here by dependency injection system automatically.
     18         /// </summary>
     19         public TaskAppService(IRepository<Task> taskRepository,)
     20         {
     21             _taskRepository = taskRepository;
     22         }
     23 
     24         public GetTasksOutput GetTasks(GetTasksInput input)
     25         {
     26             var query = _taskRepository.GetAll();
     27 
     28             if (input.AssignedPersonId.HasValue)
     29             {
     30                 query = query.Where(t => t.AssignedPersonId == input.AssignedPersonId.Value);
     31             }
     32 
     33             if (input.State.HasValue)
     34             {
     35                 query = query.Where(t => t.State == input.State.Value);
     36             }
     37 
     38             //Used AutoMapper to automatically convert List<Task> to List<TaskDto>.
     39             return new GetTasksOutput
     40             {
     41                 Tasks = Mapper.Map<List<TaskDto>>(query.ToList())
     42             };
     43         }
     44 
     45         public async Task<TaskDto> GetTaskByIdAsync(int taskId)
     46         {
     47             //Called specific GetAllWithPeople method of task repository.
     48             var task = await _taskRepository.GetAsync(taskId);
     49 
     50             //Used AutoMapper to automatically convert List<Task> to List<TaskDto>.
     51             return task.MapTo<TaskDto>();
     52         }
     53 
     54         public TaskDto GetTaskById(int taskId)
     55         {
     56             var task = _taskRepository.Get(taskId);
     57 
     58             return task.MapTo<TaskDto>();
     59         }
     60 
     61         public void UpdateTask(UpdateTaskInput input)
     62         {
     63             //We can use Logger, it's defined in ApplicationService base class.
     64             Logger.Info("Updating a task for input: " + input);
     65 
     66             //Retrieving a task entity with given id using standard Get method of repositories.
     67             var task = _taskRepository.Get(input.Id);
     68 
     69             //Updating changed properties of the retrieved task entity.
     70 
     71             if (input.State.HasValue)
     72             {
     73                 task.State = input.State.Value;
     74             }
     75 
     76             //We even do not call Update method of the repository.
     77             //Because an application service method is a 'unit of work' scope as default.
     78             //ABP automatically saves all changes when a 'unit of work' scope ends (without any exception).
     79         }
     80 
     81         public int CreateTask(CreateTaskInput input)
     82         {
     83             //We can use Logger, it's defined in ApplicationService class.
     84             Logger.Info("Creating a task for input: " + input);
     85 
     86             //Creating a new Task entity with given input's properties
     87             var task = new Task
     88             {
     89                 Description = input.Description,
     90                 Title = input.Title,
     91                 State = input.State,
     92                 CreationTime = Clock.Now
     93             };
     94 
     95             //Saving entity with standard Insert method of repositories.
     96             return _taskRepository.InsertAndGetId(task);
     97         }
     98 
     99         public void DeleteTask(int taskId)
    100         {
    101             var task = _taskRepository.Get(taskId);
    102             if (task != null)
    103             {
    104                 _taskRepository.Delete(task);
    105             }
    106         }
    107     }
    108 }
  • 相关阅读:
    通过反射将一个java对象的属性值转换为一个Map
    反射中的 Method 的 getReadMethod 与 getWriteMethod 使用 【获取一个对象的所有属性字段名称和其对应的值】
    maven项目无法导入Oracle的jdbc连接jar包【我】
    史上最全最详细JNDI数据源配置说明
    启动eclipse导致Tomcat的配置文件重置
    各种集合key,value能否为null
    CentOS系统使用yum安装配置MariaDB数据库
    Unity导出webPlayer并且部署到IIS
    unity web项目发布服务器Data file is corrupt (not a Unity W
    Unity3d Web Player 的server端联网配置
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/11047717.html
Copyright © 2020-2023  润新知