繁体   English   中英

如何在Simple Injector 3中注册AutoMapper 4

[英]How to register AutoMapper 4 with Simple Injector 3

我有一个Azure Web作业,可解析包含类别的CSV并将结果映射到常规对象中。

我正在尝试通过内存从另一个项目中的一个项目复制AutoMapper + Simple Injector配置,但出现错误:

AutoMapper.AutoMapperMappingException:缺少类型映射配置或不支持的映射。

映射类型:

CsvCategory->类别

WebJobs.Data.CsvCategory-> Data.Category

目标路径:类别

源值:WebJobs.Data.CsvCategory

container.RegisterSingleton<ITypeMapFactory, TypeMapFactory>();
container.RegisterCollection<IObjectMapper>(MapperRegistry.Mappers);
container.RegisterSingleton<ConfigurationStore>();
container.RegisterSingleton<IConfiguration, ConfigurationStore>();
container.RegisterSingleton<IConfigurationProvider, ConfigurationStore>();
container.RegisterSingleton<IMappingEngine>(Mapper.Engine);

Mapper.Initialize(c =>
{
    c.ConstructServicesUsing(container.GetInstance);
    c.AddProfile<CsvCategoryMappingProfile>();
});

public sealed class CsvCategoryMappingProfile : Profile
{
    protected override void Configure() {
        CreateMap<CsvCategory, Category>();
    }

    public override string ProfileName {
        get { return typeof(CsvCategoryMappingProfile).Name; }
    }
}

public sealed class MappingCategoryConverter : IConverter<CsvCategory, Category>
{
    private readonly IMappingEngine _mapper;

    public MappingCategoryConverter(IMappingEngine mapper)
    {
        _mapper = mapper;
    }

    public Category Convert(CsvCategory category)
    {
        return _mapper.Map<Category>(category);
    }
}

我可以通过以下行替换整个容器配置来解决此问题:

Mapper.AddProfile<CsvCategoryMappingProfile>();

但是相反,我想了解问题出在哪里,我在哪里做错了。

我看不到如何正确使用Mapper.Initialize() ,明显的方法不起作用。

解决方法:

Mapper.Initialize(x =>
{
    var config = container.GetInstance<IConfiguration>();
    config.ConstructServicesUsing(container.GetInstance);
    config.AddProfile<CsvCategoryMappingProfile>();
});

因为在x您将获得IConfiguration另一个实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM