Automapper and Autofac

时间:2015-04-29 00:33:26

标签: c# autofac automapper-3

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?

1 个答案:

答案 0 :(得分:3)

您缺少创建Mapper,在EntityMappingProfile中创建LinkEntity的地图链接:

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