AutoMapper可以将多个数据实例类型进行自动/手动的方便映射变换。对于asp.net core中的使用,我们可以如下操作

  1. 向项目中添加包
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
  1. 在程序中注册两个实例类型的注册关系
    新建一个Profile类来管理类映射关系
public class RequestProfile : Profile
{
    public RequestProfile()
    {
        CreateMap<RequestUser, RequestUserDto>().ReverseMap();
    }
}
  1. 注册配置AutoMapper
    一种简单的方式是调用AddAutoMapper 接口
builder.Services.AddAutoMapper(typeof(RequestProfile));

另一种方式是使用Configuration 进行配置

AutoMapper.IConfigurationProvider mapperConfiguration = new MapperConfiguration( cfg => {
    cfg.AddProfile<RequestProfile>();
});
builder.Services.AddSingleton(mapperConfiguration);
builder.Services.AddScoped<IMapper, Mapper>();
  1. 在控制器中注入AutoMapper对象
[ApiController]
[Route("[controller]")]
public class RequestDtoController : ControllerBase
{
    private readonly ILogger<RequestDtoController> _logger;
    private readonly IMapper _mapper;
    public RequestDtoController(ILogger<RequestDtoController> logger, IMapper mapper)
    {
        _logger = logger;
        _mapper = mapper;
    }
    
    [HttpPost]
    public IActionResult Post([FromBody] RequestUserDto requestDto)
    {
        RequestUser user = new();
        user = _mapper.Map<RequestUser>(requestDto);
        return Ok(user);
    }
}

如果两个对象的属性名称不同,则需要手动映射属性对应关系。