asp.net core 3.1.x 中使用AutoMapper

AutoMapper作用

  • AutoMapper的作用是把一个对象转化为另一个对象,避免每次都去转化;
  • 使用DTO实现表现层与领域Model的解耦,用AutoMapper来实现DTO与领域Model的相互转换;
基于访问性的控制或从模型本身上考虑。对外开放的原则是,尽量降低系统耦合度,否则内部一旦变更外部所有的接口都要跟随发生变更;另外,系统内部的一些数据或方法并不希望外部能看到或调用。类似的考虑很多,只是举个例子。系统设计的原则是高内聚低耦合,尽量依赖抽象而不依赖于具体。这里感觉automapper就是使数据库实体对一个外部调用实体的转换更简便(不用一个属性一个属性的赋值)。

AutoMapper uses a fluent configuration API to define an object-object mapping strategy. 
AutoMapper uses a convention-based matching algorithm to match up source to destination values. 
AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.

AutoMapper supports the following platforms:
.NET 4.6.1+
.NET Standard 2.0+

官网:http://automapper.org/
文档:https://automapper.readthedocs.io/en/latest/index.html
GitHub:https://github.com/AutoMapper/AutoMapper/blob/master/docs/index.rst

什么是DTO?

DTO(Data Transfer Object)就是数据传输对象(贫血模型),说白了就是一个对象,只不过里边全是数据而已。

为什么要用DTO?

  1. DTO更注重数据,对领域对象进行合理封装,从而不会将领域对象的行为过分暴露给表现层;
  2. DTO是面向UI的需求而设计的,而领域模型是面向业务而设计的。因此DTO更适合于和表现层的交互,通过DTO我们实现了表现层与领域Model之间的解耦,因此改动领域Model不会影响UI层;
  3. DTO说白了就是数据而已,不包含任何的业务逻辑,属于瘦身型(也称贫血型)的对象,使用时可以根据不同的UI需求进行灵活的运用;

应用场景

  • 对外服务接口数据模型;
  • UI层视图模型;
  • 用户的输入输出参数化模型;

如何在asp.net core 3.1.x 中应用AutoMapper实现模型转化映射?

  • Microsoft Visual Studio Enterprise 2019 版本 16.6.4;
  • .net core 3.1.7;
  • Nuget包:AutoMapper.Extensions.Microsoft.DependencyInjection -Version 8.0.1;

1. 新建项目【UseAutoMapperDemo】如下所示:

2.使用Nuget在项目中安装依赖包;

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 8.0.1

 对创建的项目改造一下,新建文件夹【Model】分别添加两个模型类【PersonA 和 PersonB】方便后面的演示使用;

2. 创建AutoMapper映射规则:在文件夹【Model】中新建类【AutoMapperProfile】配置模型的映射规则;

3. 在Startup的ConfigureServices中添加AutoMapper:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    #region 添加AutoMapper
    services.AddAutoMapper(typeof(AutoMapperProfile));
    #endregion
}

//注意:引入对应的命名空间;
using AutoMapper;
using UseAutoMapperDemo.Model;

4. 在Controller构造函数中注入你的IMapper:

#region 注册IMapper
private readonly IMapper mapper;
public ValuesController(IMapper mapper)
{
   this.mapper = mapper;
}
#endregion

5. 使用 AutoMapper 实现对象转化;

//单对象转化
var personB = mapper.Map<PersonB>(personA);

//List集合对象转化
var personBs = mapper.Map<List<PersonB>>(personAs);

以上内容就是AutoMapper在asp.net core 3.1.x的api项目中的基本使用,更多使用请查看官网;

demo项目下载:UseAutoMapperDemo.zip

猜你喜欢

转载自blog.csdn.net/ChaITSimpleLove/article/details/108019513