Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Automapper in ITypeConverter

Tags:

c#

automapper

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;
    }
}
like image 265
Thijs Avatar asked Mar 04 '16 12:03

Thijs


People also ask

When should I use AutoMapper?

AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.

Does AutoMapper work with .NET core?

AutoMapper is a ubiquitous, simple, convention-based object-to-object mapping library compatible with.NET Core. It is adept at converting an input object of one kind into an output object of a different type. You can use it to map objects of incompatible types.


1 Answers

The ResolutionContext contains a reference to the current Mapping engine. Switch the Mapper.Map with context.Engine.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.Engine.Mapper.Map.Map<Property>(src.SomeProperty);

        return result;
    }
}
like image 78
Thijs Avatar answered Oct 08 '22 22:10

Thijs