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,可自行参考。

ABP入门系列(4)——创建应用服务的更多相关文章

  1. ABP入门系列(5)——创建应用服务

    一.解释下应用服务层 应用服务用于将领域(业务)逻辑暴露给展现层.展现层通过传入DTO(数据传输对象)参数来调用应用服务,而应用服务通过领域对象来执行相应的业务逻辑并且将DTO返回给展现层.因此,展现 ...

  2. ABP入门系列(2)——通过模板创建MAP版本项目

    一.从官网创建模板项目 进入官网下载模板项目 依次按下图选择: 输入验证码开始下载 下载提示: 二.启动项目 使用VS2015打开项目,还原Nuget包: 设置以Web结尾的项目,设置为启动项目: 打 ...

  3. ABP入门系列(3)——领域层创建实体

    这一节我们主要和领域层打交道.首先我们要对ABP的体系结构以及从模板创建的解决方案进行一一对应.网上有代码生成器去简化我们这一步的任务,但是不建议初学者去使用. 一.首先来看看ABP体系结构 领域层就 ...

  4. ABP入门系列(15)——创建微信公众号模块

    ABP入门系列目录--学习Abp框架之实操演练 源码路径:Github-LearningMpaAbp 1. 引言 现在的互联网已不在仅仅局限于网页应用,IOS.Android.平板.智能家居等平台正如 ...

  5. ABP入门系列(1)——通过模板创建MAP版本项目

    ABP入门系列目录--学习Abp框架之实操演练 一.从官网创建模板项目 进入官网下载模板项目 依次按下图选择: 输入验证码开始下载 下载提示: 二.启动项目 使用VS2015打开项目,还原Nuget包 ...

  6. ABP入门系列(2)——领域层创建实体

    ABP入门系列目录--学习Abp框架之实操演练 这一节我们主要和领域层打交道.首先我们要对ABP的体系结构以及从模板创建的解决方案进行一一对应.网上有代码生成器去简化我们这一步的任务,但是不建议初学者 ...

  7. ABP入门系列(1)——学习Abp框架之实操演练

    作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...

  8. ABP入门系列(6)——展现层实现增删改查

    这一章节将通过完善Controller.View.ViewModel,来实现展现层的增删改查.最终实现效果如下图: 一.定义Controller ABP对ASP.NET MVC Controllers ...

  9. ABP入门系列(7)——分页实现

    ABP入门系列目录--学习Abp框架之实操演练 完成了任务清单的增删改查,咱们来讲一讲必不可少的的分页功能. 首先很庆幸ABP已经帮我们封装了分页实现,实在是贴心啊. 来来来,这一节咱们就来捋一捋如何 ...

随机推荐

  1. Python3学习笔记之十九

    1.    什么是orm? object  relation mapping  对象关系映射 一旦确定表关系为一对多:在多的表中添加关联字段. 一对一:可以在任意一张表添加关联字段. 多对多:创建第三 ...

  2. ERROR Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)

    1.之前搭建的kafka,过了好久,去启动kafka,发现报如下下面的错误,有错误就要解决了. 然后参考:https://blog.csdn.net/hello_world_qwp/article/d ...

  3. solution for python can not import local module

    blog 这次遇到的问题是sys.path的输出不包含'',导致无法import当前文件和文件夹 When no ._pth file is found, this is how sys.path i ...

  4. Ubuntu16.04安装cuda9.0+cudnn7.0

    Ubuntu16.04安装cuda9.0+cudnn7.0 这篇记录拖了好久,估计是去年6月份就已经安装过几遍,然后一方面因为俺比较懒,一方面后面没有经常在自己电脑上跑算法,比较少装cuda和cudn ...

  5. EF|CodeFirst数据并发管理

    在项目开发中,我们有时需要对数据并发请求进行处理.举个简单的例子,比如接单系统中,AB两个客服同时请求处理同一单时,应该只有一单请求是处理成功的,另外一单应当提示客服,此单已经被处理了,不需要再处理. ...

  6. SpringBoot报错

    同时生成了两个mapper,删除一个就行了

  7. python搭建opencv

    说明 windows下:以管理员身份使用cmd或者powershell. 安装 依次输入以下命令,安装numpy, Matplotlib, opencv三个包 pip install --upgrad ...

  8. asp.net core1.1的PlatformAbstraction源码

    PlatformAbstraction类在现在的asp.net core中已经废弃了,但是此类的设计还是不错的,可以借鉴,源码如下: namespace Microsoft.Extensions.Pl ...

  9. huginn website agent对提取结果排序

    当配置好huginn的website之后,想给提取的内容排个序,那就用下面这堆代码,因为官网里也这么说的, "events_order": [ [ "{{date_pub ...

  10. dotnetcore http服务器研究(二)性能分析

    Asp.net core kestrel 服务器性能分析 因近来发现neocli 使用asp.net core kestrel 服务器提供rpc调用,性能比较低. 和以前做过测试差异比较大,故而再次测 ...