如何使用Unity注册AutoMapper配置文件

我有以下AutoMapper配置文件:

public class AutoMapperBootstrap : Profile { protected override void Configure() { CreateMap().ForMember(x => x.NewsArticles, opt => opt.MapFrom(y => y.RssFeedContent)); CreateMap().ForMember(x => x.Id, opt => opt.Ignore()); } } 

我正在初始化它:

 var config = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperBootstrap()); }); container.RegisterInstance("Mapper", config.CreateMapper()); 

当我尝试在我的构造函数中注入它时:

 private IMapper _mapper; public RssLocalRepository(IMapper mapper) { _mapper = mapper; } 

我收到以下错误:

当前类型AutoMapper.IMapper是一个接口,无法构造。 你错过了类型映射吗?

如何使用Unity正确初始化AutoMapper配置文件,以便我可以通过DI在任何地方使用映射器?

在您的示例中,您正在创建命名映射:

 // named mapping with "Mapper name" container.RegisterInstance("Mapper", config.CreateMapper()); 

但你的解析器将如何知道这个名字?

您需要注册没有名称的映射:

 // named mapping with "Mapper name" container.RegisterInstance(config.CreateMapper()); 

它会将您的映射器实例映射到IMapper接口,并且此实例将在解析接口上返回

您可以这样注册:

 container.RegisterType(new InjectionFactory(_ => Mapper.Engine)); 

然后你可以将它注入IMappingEngine

 private IMappingEngine_mapper; public RssLocalRepository(IMappingEnginemapper) { _mapper = mapper; } 

更多信息请点击此处:

https://kalcik.net/2014/08/13/automatic-registration-of-automapper-profiles-with-the-unity-dependency-injection-container/