1. 引用AutoMapper.Extensions.Microsoft.Dependencylnjection包

  2. 组织映射配置的一个好方法是使用配置文件。创建继承自Profile并将配置放入构造函数的类

     public class RBACProfile: Profile
        {
            public RBACProfile()
            {
                CreateMap<xxxDto,xxx>();
            }
        }
    
  3. Program.cs中标记

    //AutoMapper
    builder.Services.AddAutoMapper(typeof(RBACProfile));
    
  4. 在运行时将 AutoMapper 注入您的服务/控制器

    IService _Service;
    private readonly IMapper _mapper;
    public RoleController(IService Service, IMapper mapper)
    {
        _Service = Service;
        _mapper = mapper;
    }
    
    [HttpPost("Create")]
    public IActionResult Create(xxxDto dto)
    {
       var result = _mapper.Map<xxx>(dto);
       return Ok(_Service.Create(result));
    }
    
posted on 2022-09-25 21:34  Coriander_Leo  阅读(390)  评论(0编辑  收藏  举报