簡體   English   中英

使用Automapper根據源上的值映射到特定的派生類型

[英]Map to specific derived type based on value on source using Automapper

在源是一個應根據源值映射到兩個派生類之一的類的情況下,實現Automapper轉換時遇到麻煩。

這是我的課程的簡化:

public class FooContainerDTO
{
    public FooDTO Foo { get; set; } 
}

public class FooDTO
{
    public string Type { get; set; }

    //some properties..
}

public class FooContainer
{
    public FooBase Foo { get; set; }
}

public abastract class FooBase
{
    //some properties..
}

public class FooDerived1 : FooBase
{
    //some properties
}

public class FooDerived2 : FooBase
{
    //some properties
}

我使用的是非靜態Automapper,因此我在啟動時根據多個配置文件創建了一個MapperConfiguration,並將IMapper實例注入到我的DI容器中。 我希望Automapper將FooDTO的Type屬性為“ der1”時映射到FooDerived1,而將其為“ der2”時映射​​到FooDerived2。

我已經看到了使用靜態api的示例,如下所示:

 Mapper.CreateMap<FooContainerDTO, FooContainer>();
        //ForMember configurations etc.

 Mapper.CreateMap<FooDTO, FooDerived1>();
        //ForMember configurations etc.

 Mapper.CreateMap<FooDTO, FooDerived2>();
        //ForMember configurations etc.

 Mapper.CreateMap<FooDTO, FooBase>()
       .ConvertUsing(dto => dto.Type == "der1"
           ? (FooBase) Mapper.Map<FooDerived1>(dto)
           : Mapper.Map<FooDerived2>(dto));

這會將FooContainer的Foo屬性映射到FooBase的正確派生類型。

但是,如何在沒有靜態API的情況下執行此操作? 在配置文件時尚未創建IMapper實例。 有沒有一種方法可以利用需要Func <ResolutionContext,object>的ConvertUsing()的重載? 解析上下文可以為我提供當前正在使用的IMapper嗎? 我一直在尋找,但是找不到任何可用的東西。

一種訪問映射引擎的方法是通過您自己的TypeConverter

abstract class MyTypeConverter<TSource,TDestination> : ITypeConverter<TSource, TDestination>
{
    protected ResolutionContext context;
    public TDestination Convert(ResolutionContext context)
    {
        this.context = context;
        return Convert((TSource)context.SourceValue);
    }
    public abstract TDestination Convert(TSource source);
}

然后,您創建一個實際的實現,例如:

class MyTypeMapper : MyTypeConverter<EnumType,EnumTypeView>
{
    public override EnumTypeView Convert(EnumType source)
    {
        return context.Engine.Mapper.Map<EnumTypeID, EnumTypeView>(source.EnumBaseType);
    }
}

除了不解開枚舉結構外,您還要檢查類型並使用其他類型調用Map。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM