2018年8月12日 星期日

[ASP.NET Core] AutoMapper mappings


 ASP.NET Core   AutoMapper    Injection


Introduction


This article shows 2 ways to set AutoMapper mappings in ASP.NET Core 2.X.

1.  Static factory
2.  Injection


Environment


.NET Core 2.1.300
AutoMapper 7.0.1
AutoMapper.Extensions.Microsoft.DependencyInjection 5.0.1



Implement


Method 1. Static factory

This is my prefer way for using AutoMapper in both web and library projects.

AutoMapFactory.cs

using AutoMapper;

public class AutoMapFactory
{
        private static IMapper MAPPER = null;

        static DtoFactory()
        {
            MapperConfiguration mapCfg = new MapperConfiguration(cfg =>
                       {
                        
                           #region X1 => X2
                           cfg.CreateMap<X1, X2>();
                           #endregion
                       });

            MAPPER = mapCfg.CreateMapper();
        }

        public static K Create<T, K>(T src)
        {
            var dest = MAPPER.Map<T, K>(src);
            return dest;
        }

        public static List<K> Create<T, K>(List<T> srcCollection)
        {
            return srcCollection.Select(x => MAPPER.Map<T, K>(x)).ToList();
        }
    }


Usage:


public class ProdController : BaseController
{
        [HttpPost("Create")]
        [AllowAnonymous]
        public async Task<HttpResponseMessage> Create([FromBody]X1 data)
        {
            //Use static factory
            var poco = DaoAutoMapFactory.Create<X1, X2>(data);

            //…
        }
}




Method 2: Injection

Install AutoMapper.Extensions.Microsoft.DependencyInjection in the ASP.NET Core project.

Now let’s create a mapping profile for later injection. Notice that you can put this profile in the website project or netstandard project.

MappingProfile.cs

using AutoMapper;

namespace My.Service.Mapper
{
    public class MappingProfile:Profile
    {
        public MappingProfile()
        {
            #region X1 => X2
            CreateMap<X1, X2>();
            #endregion
        }
}


Lets inject it in Startup.cs as following.


Startup.cs

public class Startup
{
   public void ConfigureServices(IServiceCollection services)
   {
            services.AddMvc();
services.AddAutoMapper(
typeof(My.Service.Mapper.MappingProfile).GetTypeInfo().Assembly);
   }
}


Usage:

public class ProdController : BaseController
{
        private IMapper _mapper = null;

        public ProdController(IMapper mapper)
        {
            this._mapper = mapper;
        }

        [HttpPost("Create")]
        [AllowAnonymous]
        public async Task<HttpResponseMessage> Create([FromBody]X1 data)
        {
            //User injection service
            var poco = this._mapper.Map<X1, X2>(data);

            //…
        }
}




Reference




沒有留言:

張貼留言