在自定义类型转换器中调用 Mapper.Map

Call Mapper.Map inside a custom type converter

我知道这个问题已经被问过一次 here 但没有必要在自定义类型转换器中调用 Automapper.Map() 方法。那么如果我有这种类型的结构呢:

class MyType
{
    public double ValueToBeComputed1 { get; set; }

    public double ValueToBeComputed2 { get; set; }
}

class ComplexType
{
    public double ValueToBeComputed { get; set; }
    public MyType MyProperty { get; set; }
}

对于要计算的所有值,我需要进行不同的演算,因此我将有一个用于复杂类型的自定义类型转换器,比如 OtherType。我的问题是我是否能够为自定义转换器中的 属性 MyProperty 调用 Mapper.Map()?

在我面对Automapper自定义类型转换器的过时文档后,其中ITypeConverter接口已被更改,我在这里找到了答案: ITypeConverter interface has been changed in AutoMapper 2.0 ,我能够制作一个工作原型,它生成如下转换类型:

public class ComplexTypeConverter : ITypeConverter<ComplexSourceType, ComplexDestinationType>
{
    public ComplexDestinationType Convert(ResolutionContext context)
    {
        var source = (ComplexSourceType)context.SourceValue;

        return new ComplexDestinationType
        {
            MyProperty = Mapper.Map<SourceType, DestinationType>(source.MyProperty),
            ValueComputed = source.ValueToBeComputed + 10
        };
    }
}

public class TypeConverter : ITypeConverter<SourceType, DestinationType>
{
    public DestinationType Convert(ResolutionContext context)
    {
        var source= (SourceType)context.SourceValue;
        return new DestinationType
        {
            ValueComputed1 = source.ValueToBeComputed1 + 10,
            ValueComputed2 = source.ValueToBeComputed2 + 10
        };
    }
}

class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(cfg => {
            cfg.CreateMap<ComplexSourceType, ComplexDestinationType>().ConvertUsing(new ComplexTypeConverter());
            cfg.CreateMap<SourceType, DestinationType>().ConvertUsing(new TypeConverter());
        });

        Mapper.AssertConfigurationIsValid();

        ComplexSourceType source = new ComplexSourceType
        {
            MyProperty = new SourceType
            {
                ValueToBeComputed1 = 1,
                ValueToBeComputed2 = 1
            },
            ValueToBeComputed = 1
        };
        var dest = Mapper.Map<ComplexSourceType, ComplexDestinationType>(source);
    }
}

dest 对象保存修改后的数据,每个 11 属性