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

Ken*_*nci 4 c# unity-container automapper

我有以下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());
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在这样初始化它:

var config = new MapperConfiguration(cfg =>
{
       cfg.AddProfile(new AutoMapperBootstrap());
});

container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());
Run Code Online (Sandbox Code Playgroud)

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

private IMapper _mapper;
public RssLocalRepository(IMapper mapper)
{
    _mapper = mapper;
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

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

MaK*_*MKo 11

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

// named mapping with "Mapper name"
container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());
Run Code Online (Sandbox Code Playgroud)

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

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

// named mapping with "Mapper name"
container.RegisterInstance<IMapper>(config.CreateMapper());
Run Code Online (Sandbox Code Playgroud)

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