我正在尝试在应用程序中实现一些横切关注点,该应用程序使用AutoMapper在不同的DTO /消息对象之间进行映射。

说我有这个:
configuration.Map<MyMessage, MyEvent>()MyEvent实现IEvent(这是没有属性的标记接口)。有什么方法可以要求AutoMapper将MyMessage映射到IEvent,并推断出“哦,我将MyMessage映射到MyEvent,并且MyEvent实现了IEvent”?

这个(无效的)示例显示了我想要实现的目标:

// IEvent is just a marker interface with no properties,
// and is implemented by all of the *Event classes

configuration.CreateMap<MyMessage, MyEvent>();
configuration.CreateMap<MyOtherMessage, MyOtherEvent>();
// etc.

// ... somewhere else in the code ...

public class MyCrossCuttingThing<TMessage>
{
    private readonly IMapper _mapper;

    // ... code that does stuff ...

    public void DoThing(TMessage message)
    {
        // ... more code ...

        var @event = _mapper.Map<IEvent>(message);

        // Here I would expect @event to be a MyEvent instance if
        // TMessage is MyMessage, for example
    }
}


这给了我一个例外:


  缺少类型映射配置或不支持的映射。


我尝试将.Include.IncludeBase添加到CreateMap语句,但是结果相同。有什么方法可以实现我想要的,还是这根本不是受支持的用例?

最佳答案

对于这种简单的情况,您可以使用As。

CreateMap<MyMessage, IEvent>().As<MyEvent>();


假设IEvent是标记接口,则还需要具体的映射MyMessage => MyEvent。
如果实际情况更复杂,则需要包括。 docs

关于c# - 通过与AutoMapper的接口(interface)推断目标类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45634493/

10-10 12:36