user2963570
user2963570

Reputation: 381

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?

Upvotes: 1

Views: 3266

Answers (2)

user2963570
user2963570

Reputation: 381

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>));
}

Upvotes: 0

Aleksey L.
Aleksey L.

Reputation: 38046

You can specify DTO type in BaseService as generic parameter:

public class BaseService<T, TDTO> : IService<T, TDTO> 
    where T : class, IEntity
    where TDTO : class, IEntityDTO
{
    private IRepository<T> _repository;
...
...
    public IList<TDTO> GetAll()
    {
        return _mapper.Map<IList<TDTO>>(_repository.GetAll().ToList());
    }
}

Upvotes: 2

Related Questions