我正在尝试让Automapper在 ASP.Net MVC应用程序中与Autofac配合得很好。
我已经按照答案中的说明进行操作:Autofac 3和Automapper
但是,它在第一次调用_mapper.Map<>(...)
时失败
Autofac的设置如下:
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>();
然后在我的业务层中,我有这样的服务:
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);
}
}
对_mapper.Map<IEnumerable<Link>, IEnumerable<LinkEntity>>
的召唤失败,并显示:
缺少类型映射配置或不受支持的映射。
有什么想法我可能出错吗?
您缺少创建映射器,请在EntityMappingProfile中创建指向LinkEntity的映射链接:
internal class EntityMappingProfile :Profile
{
protected override void Configure()
{
base.Configure();
this.CreateMap<Link, LinkEntity>();
}
}