Automapper - CreateMap 被多次调用

2024-05-09

当我多次调用相同类型的 Mapper.CreateMap 时会发生什么?

它会重写之前的地图吗?如果是这样,如果我尝试创建已经创建的地图,是否可以使其抛出异常?


当多次为同一组源和目标调用 Mapper.CreateMap 时,根本不会发生任何事情,因为Mapper.CreateMap<TSource, TDestination>()不为映射配置设置任何扩展。 如果您像这样设置 IMappingExpression 的覆盖Mapper.CreateMap<TSource, TDestination>().ConstructUsing(x=>new TDestination(x.SomeField)), 如果是的话,该映射的配置将被新的配置替换。 关于您问题的第二部分,我知道验证地图是否已创建的方法:

public TDestination Resolve<TSource, TDestination>(TSource source)
{
     var mapped = Mapper.FindTypeMapFor(typeof(TSource), typeof(TDestination)); //this will give you a reference to existing mapping if it was created or NULL if not

     if (mapped == null)
     {
        var expression = Mapper.CreateMap<TSource, TDestination>();
     }
     return Mapper.Map<TSource, TDestination>(source);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Automapper - CreateMap 被多次调用 的相关文章

随机推荐