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

How to register an AutoMapper profile with Unity

我有以下 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;
}

我收到以下错误:

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 接口,并且该实例将在解析接口时返回

您可以这样注册:

container.RegisterType<IMappingEngine>(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/