通过与AutoMapper的接口推断目标类型 [英] Inferring destination type from interface with AutoMapper
问题描述
我正在尝试在应用程序中实现一些横切关注点,该应用程序使用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. 如果实际情况更复杂,则需要包括. 文档.
I'm trying to implement some cross-cutting concerns in my application, which uses AutoMapper to map between different DTOs/message objects.
Say I have this:
configuration.Map<MyMessage, MyEvent>()
. MyEvent
implements IEvent
(which is a marker interface with no properties). Is there any way to ask AutoMapper to map a MyMessage
to IEvent
, and have it infer that "oh, I have a mapping MyMessage
to MyEvent
, and MyEvent
implements IEvent
"?
This (invalid) example shows what I want to achieve:
// 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
}
}
This gives me an exception:
Missing type map configuration or unsupported mapping.
I've tried adding .Include
or .IncludeBase
to the CreateMap
statement, but same result. Is there any way to achieve what I want, or is this simply not a supported use case?
For this simple case you can use As.
CreateMap<MyMessage, IEvent>().As<MyEvent>();
Given that IEvent is a marker interface, you need also the concrete map MyMessage=>MyEvent. If your real case is more complicated, you need Include. The docs.
这篇关于通过与AutoMapper的接口推断目标类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!