我试图让Automapper在ASP.Net MVC应用程序中与Autofac配合使用.
我已按照答案中的说明进行操作:Autofac 3 and 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>>的调用
失败了:
Missing type map configuration or unsupported mapping.
我可能会出错的任何想法?
解决方法:
你缺少创建Mapper,在EntityMappingProfile中创建LinkEntity的地图链接:
internal class EntityMappingProfile :Profile
{
protected override void Configure()
{
base.Configure();
this.CreateMap<Link, LinkEntity>();
}
}