Search code examples
c#dependency-injectionautomappersimple-injectorautomapper-4

How to register AutoMapper 4 with Simple Injector 3


I have an Azure web job that parses CSV containing categories and maps the result into regular objects.

I'm trying to replicate AutoMapper + Simple Injector configuration from one project in another by memory but getting an error:

AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping.

Mapping types:

CsvCategory -> Category

WebJobs.Data.CsvCategory -> Data.Category

Destination path: Category

Source value: 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);
    }
}

I can fix it by replacing the whole container configuration with this line:

Mapper.AddProfile<CsvCategoryMappingProfile>();

but instead I'd like to learn where is the problem, where I'm doing this wrong.


Solution

  • I don't see how to use Mapper.Initialize() properly, the obvious way doesn't work.

    Here's a workaround:

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

    Because at x you're getting another instance of IConfiguration.