6
votes

I'm trying to use automapper and have some issues when trying to resolve a mapper object.

This is the code

 public class MapAdapter : IMyMapper
 {
        private readonly AutoMapper.IMapper _mapper;

        public MapAdapter(AutoMapper.IMapper mapper)
        {
            _mapper = mapper;
        }

public TDest Map<TSource, TDest>(TSource source)
        {
            try
            {
                return _mapper.Map<TSource, TDest>(source);
            }
            catch (Exception exception)
            {
                throw;
            }
        }
}

And this is the exception

An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'AutoMapper.IMapper' while attempting to activate 'Infrastructure.Mapper.Adapter.MapAdapter'.

If i remvoe the AutoMapper.Mapper dependency from constructor

public MapAdapter()

everything works, except for the Automapper _mapper field which of course is null

This is the DI configuration, where IMyMapper is my interface, and MapAdapter is the Implementation of IMyMapper

_serviceCollection.AddTransient<IMyMapper, MapAdapter>();

I have a mapping profile which is empty

  public class OrderDataMappingProfile : Profile
    {
        public OrderDataMappingProfile()
        {
        }
    }

any idea why this fails ?

1
@MCR, any reason why you unselected my answer as the correct answer? - Marcus Höglund
sorry, no. it is the preferred answer - user9124444

1 Answers

4
votes

This error occours because you haven't registered a mapper which should be resolved on the IMapper interface on the service collection.

To solve it, add the mapping profile to a new mapper configuration and then create a mapper from that and bind it to the collection.

var config = new AutoMapper.MapperConfiguration(cfg =>
{
    cfg.AddProfile(new OrderDataMappingProfile ());
});
var mapper = config.CreateMapper();
_serviceCollection.AddSingleton(mapper);