学海无涯

导航

AutoMapper 对象映射器

https://docs.automapper.org/

基于约定的对象-对象映射器。100% 有机和无麸质。消除将一个对象映射到另一个对象的所有麻烦。

什么是 AutoMapper?

AutoMapper 是一个简单的小库,旨在解决一个看似复杂的问题——摆脱将一个对象映射到另一个对象的代码。这种类型的代码写起来相当枯燥乏味,那么为什么不发明一个工具来为我们做呢?

 映射可以出现在应用程序的许多地方,但主要是在层之间的边界,例如 UI/Domain 层或 Service/Domain 层之间。一层的关注点经常与另一层的关注点发生冲突,因此对象-对象映射导致分离模型,其中每一层的关注点只能影响该层中的类型。

1. NuGet引用 
AutoMapper

AutoMapper.Extensions.Microsoft.DependencyInjection

2. 添加继承 Profile 的映射关系类 MappingProfile

using AutoMapper;
using TestWebApplication.Model;

namespace TestWebApplication.Extensions
{
    public class MappingProfile:Profile
    {
        public MappingProfile()
        {
            CreateMap<Post, PostResource>()
                .ForMember(d=>d.UpdateTime,s=>s.MapFrom(src=>src.LastModified));
            CreateMap<PostResource, Post>();
            CreateMap<PO, POResource>();
            CreateMap<POResource, PO>();
        }
    }
}

3. 注册服务

builder.Services.AddAutoMapper(typeof(MappingProfile));

4. 客户通过注入IMapper 消费

using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TestWebApplication.Model;

namespace TestWebApplication.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestAutoMapperController : ControllerBase
    {
        private readonly ILogger<TestAutoMapperController> _logger;
        private readonly IMapper _mapper;
        private readonly ApplicationDbContext _context;
        public TestAutoMapperController(ILogger<TestAutoMapperController> logger, IMapper mapper, ApplicationDbContext context)
        {
            _logger = logger;
            _mapper = mapper;
            _context = context;
        }

        [HttpGet(nameof(GetPostResource))]
        public async Task<ActionResult<PostResource>> GetPostResource()
        {
            Post post = new Post
            {
                Title = "ASP.NET Core 项目实战",
                Author = "杨中科",
                Body = "基于DDD与前扣端分离",
                LastModified = DateTime.Now,
                Remark = "From:" + nameof(Post)
            };
            PostResource postResource = _mapper.Map<Post, PostResource>(post);
            postResource.Remark += $" To {nameof(PostResource)}";
            return Ok(postResource);
        }
        [HttpGet(nameof(GetPost))]
        public async Task<ActionResult<Post>> GetPost()
        {
            PostResource postResource = new PostResource
            {
                Title = "ASP.NET Core 项目实战",
                Author = "杨中科",
                Body = "基于DDD与前扣端分离",
                UpdateTime = DateTime.Now,
                Remark = "From:" + nameof(PostResource)
            };
            Post post = _mapper.Map<PostResource, Post>(postResource);
            post.Remark += $" To {nameof(Post)}";
            return Ok(post);
        }
        [HttpGet(nameof(GetPO))]
        public async Task<ActionResult<IEnumerable<POResource>>> GetPO()
        {
            var poList = await _context.PO.Take(3).ToListAsync();
            IEnumerable<POResource> poResources = _mapper.Map<IEnumerable<PO>, IEnumerable<POResource>>(poList);
            return Ok(poResources);
        }
    }
}

  

 在AutoFac中注册:

https://www.cnblogs.com/friend/p/16915214.html

posted on 2022-09-17 20:14  宁静致远.  阅读(71)  评论(0编辑  收藏  举报