Automapper Map from Interface to dynamic while deciding implementation destination based on value

Viewed 186

I'm trying to select what the interface will convert to. So I have the maps set up like this:

    CreateMap<ICustomerServiceDto, dynamic>()
        .ConvertUsing(service => CreateForServices(service));
    CreateMap<ICustomerServiceDto, CustomerServiceTelecomDto>();
    CreateMap<CustomerServiceTelecomDto, CustomerServiceTelecomModel>();

And the CreateForServices

    private ICustomerServiceModel CreateForServices(ICustomerServiceDto type)
    {
        if (type is CustomerServiceTelecomDto telecom)
        {
            //I do not like this solution
            return new CustomerServiceTelecomModel(telecom.Value);
        }


        throw new InvalidOperationException($"Unknown type: {type.GetType().FullName}");
    }

I will add other types to convert to later, but the above is working.

But I would prefer not have to populate the constructor in the CustomerServiceTelecomModel, AutoMapper already knows how to map a CustomerServiceTelecomDto to CustomerServiceTelecomModel so can I use that Mapping somehow?

This is inside a Mapper Profile so as far as I know I cannot access a mapper instance and do the mapping manually.

1 Answers

You can use another overload of ConvertUsing which provides the resolution context and a reference to the mapper with it.

    CreateMap<ICustomerServiceDto, dynamic>()
        .ConvertUsing((service, _, ctx) => CreateForServices(ctx, service));

    private ICustomerServiceModel CreateForServices(ResolutionContext ctx, ICustomerServiceDto type)
    {
        if (type is CustomerServiceTelecomDto telecom)
        {
            return ctx.Mapper.Map<CustomerServiceTelecomModel>(type);
        }


        throw new InvalidOperationException($"Unknown type: {type.GetType().FullName}");
    }
Related