Search code examples
c#automapper-5

C# Automapper Generic Mapping


When playing around with AutoMapper I was wondering whether the following is possible to implement like this (haven't been able to set it up correctly).

Base Service:

public class BaseService<T, IEntityDTO> : IService<T, IEntityDTO> where T : class, IEntity
{
    private IUnitOfWork _unitOfWork;
    private IRepository<IEntity> _repository;
    private IMapper _mapper;

    public BaseService(IUnitOfWork unitOfWork, IMapper mapper)
    {
        _unitOfWork = unitOfWork;
        _repository = unitOfWork.Repository<IEntity>();
        _mapper = mapper;
    }

    public IList<IEntityDTO> GetAll()
    {
        return _mapper.Map<IList<IEntityDTO>>(_repository.GetAll().ToList());
    }
}

Concrete Service:

public class HotelService : BaseService<Hotels, HotelsDTO>, IHotelService
{

    private IUnitOfWork _unitOfWork;
    private IRepository<Hotels> _hotelsRepository;
    private IMapper _mapper;

    public HotelService(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper)
    {
        _unitOfWork = unitOfWork;
        _hotelsRepository = unitOfWork.Repository<Hotels>();
        _mapper = mapper;
    }
}

Current mappings:

public class AutoMapperProfileConfiguration : Profile
{
    protected override void Configure()
    {
        CreateMap<Hotels, HotelsDTO>().ReverseMap();
    }
}

I'm kindly clueless on how the mapping should be done. Anyone any advice or is this just not the way to go?


Solution

  • Managed to solve my problem with the following line of code which looks up the mapping of the passed entity to the basecontroller.

    public List<TDTO> GetAll()
    {
        var list = _repository.GetAll().ToList();
        return (List<TDTO>)_mapper.Map(list, list.GetType(), typeof(IList<TDTO>));
    }