Search code examples
c#autofacautomapper-3

Automapper and Autofac


I am trying to get Automapper to play nice with Autofac in an ASP.Net MVC application.

I have followed the instructions in the answer to this: Autofac 3 and Automapper

However it fails on the first call to _mapper.Map<>(...)

Autofac is setup like this:

builder.RegisterType<EntityMappingProfile>().As<Profile>();

builder.Register(ctx => new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers))
    .AsImplementedInterfaces()
    .SingleInstance()
    .OnActivating(x =>
    {
        foreach (var profile in x.Context.Resolve<IEnumerable<Profile>>())
        {
            x.Instance.AddProfile(profile);
        }
    });

builder.RegisterType<MappingEngine>().As<IMappingEngine>();

and then in my business layer I have a service like this:

public class LinkService : ILinkService
{
    private readonly ILinkRepository _linkRepository;
    private readonly IMappingEngine _mapper;
    public LinkService(ILinkRepository linkRepository, IMappingEngine mapper)
    {
        _linkRepository = linkRepository;
        _mapper = mapper;

    }

    public IEnumerable<LinkEntity> Get()
    {
        var links = _linkRepository.Get().ToList();
        return _mapper.Map<IEnumerable<Link>, IEnumerable<LinkEntity>>(links);
    }

    public LinkEntity GetById(int id)
    {
        var link = _linkRepository.GetById(id);
        return _mapper.Map<Link, LinkEntity>(link);
    }
}

The call to _mapper.Map<IEnumerable<Link>, IEnumerable<LinkEntity>> fails with:

Missing type map configuration or unsupported mapping.

Any ideas where I might be going wrong?


Solution

  • you're missing creating Mapper, create map Link to LinkEntity in EntityMappingProfile:

      internal class EntityMappingProfile :Profile
    {
        protected override void Configure()
        {
            base.Configure();
            this.CreateMap<Link, LinkEntity>();
        }
    }