Inferring destination type from interface with AutoMapper

空扰寡人 提交于 2019-12-06 05:40:28

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.

I figured out a way of achieving what I want:

configuration.CreateMap<MyMessage, MyEvent>();
configuration.CreateMap<MyMessage, IEvent>()
    .ConstructUsing((m, c) => c.Mapper.Map<MyMessage, MyEvent>(m));

configuration.CreateMap<MyOtherMessage, MyOtherEvent>();
configuration.CreateMap<MyOtherMessage, IEvent>()
    .ConstructUsing((m, c) => c.Mapper.Map<MyOtherMessage, MyOtherEvent>(m));

// etc. - will encapsulate in an extension method

By registering the mappings like this, AutoMapper finds the correct mapper based on the TMessage type and gives me back an event instance. Just as simple as I'd hoped!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!