2016-04-21 82 views
3

註冊一個AutoMapper輪廓,我有以下AutoMapper簡介:如何使用Unity

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()); 
    } 
} 

而且我初始化這樣的:

​​

當我嘗試在我的構造函數注入它:

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

我收到以下錯誤:

The current type, AutoMapper.IMapper, is an interface and cannot be constructed. Are you missing a type mapping?

如何使用Unity正確初始化AutoMapper配置文件,以便通過DI在任何位置使用映射器?

回答

8

在你的榜樣,你正在創建一個名爲映射:

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

但是你解析如何知道這個名字嗎?

您需要註冊你的映射沒有名字:

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

將你的映射器實例映射到IMapper接口和這種情況下將在解決接口