我有以下 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());
当我尝试将它注入(inject)我的构造函数时:
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 在任何地方使用映射器?
最佳答案
在您的示例中,您正在创建命名映射:
// named mapping with "Mapper name"
container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());
但是您的解析器如何知道这个名称呢?
你需要在没有名字的情况下注册你的映射:
// named mapping with "Mapper name"
container.RegisterInstance<IMapper>(config.CreateMapper());
它将您的映射器实例映射到IMapper
接口(interface),并且该实例将在解析接口(interface)时返回
关于c# - 如何使用 Unity 注册 AutoMapper 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36780573/