Automapper 和 Autofac
Automapper and Autofac
我正在尝试让 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,创建映射 Link 到 LinkEntityMappingProfile 中的实体:
internal class EntityMappingProfile :Profile
{
protected override void Configure()
{
base.Configure();
this.CreateMap<Link, LinkEntity>();
}
}
我正在尝试让 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,创建映射 Link 到 LinkEntityMappingProfile 中的实体:
internal class EntityMappingProfile :Profile
{
protected override void Configure()
{
base.Configure();
this.CreateMap<Link, LinkEntity>();
}
}