Skip to content

Working with AutoMapper.

Arik1337 edited this page Mar 31, 2021 · 3 revisions

AutoMapper is a library designed to help us map from one object to another. In our project we will use AutoMapper to map between DTO and Domain objects back and forth.

Here's a little example to get you started:

public class StoresService : IStoresService
{
    private readonly ILogger<StoresService> _logger;
    private readonly IMapper _mapper;

    public StoresService(ILogger<StoresService> logger, IMapper mapper)
    {
        _logger = logger;
        _mapper = mapper;
    }
}

Every service will receive an IMapper in his constructor and will later be injected to it.

In order for the IMapper to work we must first provide a mapping. In the "BoomaEcommerce.Services" project you will see a folder "MappingProfiles" that contains the mapping classes.

Here's an example of adding a mapping to a Store class to StoreDto:

namespace BoomaEcommerce.Services.MappingProfiles
{
    public class DomainToDtoProfile : Profile
    {
        /// <summary>
        /// A class that holds all the mappings from Domain objects to DTO objects.
        /// </summary>
        public DomainToDtoProfile()
        {
            CreateMap<Store, StoreDto>();
        }
    }
}

And here's the reversed mapping: (Notice it's in a different class)

namespace BoomaEcommerce.Services.MappingProfiles
{
    /// <summary>
    /// A class that holds all the mappings from DTO objects to Domain objects.
    /// </summary>
    public class DtoToDomainProfile : Profile
    {
        public DtoToDomainProfile()
        {
            CreateMap<StoreDto, Store>();
        }
    }
}

This is of course a really simple mapping and much more complicated mappings can be created, but this will suffice for most scenarios. Also every Object field a Store\StoreDto has must also be provided as a mapping. for example, if a Store class has Product in his field the mapping for Product to ProductDto must be provided.

This is how you use the IMapper after you've created the mapping:

public async Task<StoreDto> GetStoreAsync(Guid storeGuid)
{
    var store = new Store();
    StoreDto storeDto = _mapper.Map<StoreDto>(store);
    return storeDto;
}

Clone this wiki locally