Thijs
Thijs

Reputation: 3055

Use Automapper in ITypeConverter

I'm upgrading AutoMapper in a project, converting from the static Mapper.CreateMap to the new way and injecting a IMapper where I need to map.

This is going great except for one use case. I have several ITypeConverters for complex mapping which are using the Mapper.Map function. How can I fix this? Below is the code I'm using at the moment.

The static Mapper.Map can't find my defined mappings because the're not being created using the static method.

public partial class ApplicationMappingsProfile
{
    private void RegisterMappings()
    {
        CreateMap<Application, AppDto>()
            .ConvertUsing<ApplicationTypeConverter>();
    }
}

private class ApplicationTypeConverter : ITypeConverter<App, AppDto>
{
    public AppDto Convert(ResolutionContext context)
    {
        var src = context.SourceValue as App;
        if (src == null)
        {
            return null;
        }

        var dto = Mapper.Map<App, AppDto>(src);
        dto.property = Mapper.Map<Property>(src.SomeProperty);

        return result;
    }
}

Upvotes: 12

Views: 10659

Answers (1)

Thijs
Thijs

Reputation: 3055

The ResolutionContext contains a reference to the current Mapping engine. Switch the Mapper.Map with context.Mapper.Map and you're good to go.

public partial class ApplicationMappingsProfile
{
    private void RegisterMappings()
    {
        CreateMap<Application, AppDto>()
            .ConvertUsing<ApplicationTypeConverter>();
    }
}

private class ApplicationTypeConverter : ITypeConverter<App, AppDto>
{
    public AppDto Convert(ResolutionContext context)
    {
        var src = context.SourceValue as App;
        if (src == null)
        {
            return null;
        }

        var dto = Mapper.Map<App, AppDto>(src);
        dto.property = context.Mapper.Map<Property>(src.SomeProperty);

        return result;
    }
}

Upvotes: 18

Related Questions