代码之家  ›  专栏  ›  技术社区  ›  Martin Wedvich

从与AutoMapper的接口推断目标类型

  •  2
  • Martin Wedvich  · 技术社区  · 7 年前

    我试图在我的应用程序中实现一些交叉关注点,它使用AutoMapper在不同的DTO/message对象之间映射。

    假设我有这个: configuration.Map<MyMessage, MyEvent>() . MyEvent IEvent (这是一个没有属性的标记接口)。有没有办法让AutoMapper映射 MyMessage I事件 我的消息 MyEvent公司 MyEvent公司 I事件 "?

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

    // 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

    2 回复  |  直到 7 年前
        1
  •  4
  •   Lucian Bargaoanu    4 年前

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

    鉴于此 IEvent 是一个标记界面,你还需要具体的地图 MyMessage MyEvent . 如果你的真实情况更复杂,你需要 Include 这个 docs

        2
  •  0
  •   Martin Wedvich    7 年前

    我想出了一种实现我想要的东西的方法:

    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
    

    通过这样注册映射,AutoMapper可以根据 TMessage 键入并返回一个事件实例。就像我希望的那样简单!