我有以下AutoMapper个人资料:
public class AutoMapperBootstrap : Profile
{
protected override void Configure()
{
CreateMap<Data.EntityFramework.RssFeed, IRssFeed>().ForMember(x => x.NewsArticles, opt => opt.MapFrom(y => y.RssFeedContent));
CreateMap<IRssFeedContent, Data.EntityFramework.RssFeedContent>().ForMember(x => x.Id, opt => opt.Ignore());
}
}
我正在初始化它:
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperBootstrap());
});
container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());
当我尝试在构造函数中注入它时:
private IMapper _mapper;
public RssLocalRepository(IMapper mapper)
{
_mapper = mapper;
}
我收到以下错误:
当前类型AutoMapper.IMapper是一个接口,不能 建造。你错过了类型映射吗?
如何使用Unity正确初始化AutoMapper配置文件,以便我可以通过DI在任何地方使用映射器?
答案 0 :(得分:9)
在您的示例中,您正在创建命名映射:
// named mapping with "Mapper name"
container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());
但你的解析器将如何知道这个名字?
您需要注册没有名称的映射:
// named mapping with "Mapper name"
container.RegisterInstance<IMapper>(config.CreateMapper());
它会将您的映射器实例映射到IMapper
接口,此实例将在解析接口上返回
答案 1 :(得分:1)
你可以这样注册:
http://code.ionicframework.com/resources/splash.psd
然后您可以将其注入- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId" forIndexPath:indexPath];
cell.image = image;
cell.imageViewHeightConstraint.constant = [self calcuteSizeWithImage:image]; //you need to do the calculation yourself
return cell;
}
。
container.RegisterType<IMappingEngine>(new InjectionFactory(_ => Mapper.Engine));
更多信息请点击此处: