AutoMapper使用错误的构造函数

今天我使用AutoMapper v1.1升级了一个function齐全的应用程序,现在使用AutoMapper v2.1,我遇到了一些我以前从未遇到的问题。

这是我的代码从Dto映射回Domain对象的示例

public class TypeOne { public TypeOne() { } public TypeOne(TypeTwo two) { //throw ex if two is null } public TypeOne(TypeTwo two, TypeThree three) { //throw ex if two or three are null } public TypeTwo Two {get; private set;} public TypeThree Three {get; private set;} } public class TypeOneDto { public TypeOneDto() { } public TypeTwoDto Two {get; set;} public TypeThreeDto Three {get; set;} } 

 Mapper.CreateMap(); Mapper.CreateMap(); Mapper.CreateMap(); var typeOne = Mapper.Map(typeOneDto); 

然而,我在v2.1中遇到的第一个问题是,当其中一个args为null并且应该使用1个arg构造函数时,AutoMapper尝试使用带有2个args的构造函数。

然后我尝试使用

 Mapper.CreateMap().ConstructUsing(x => new TypeOne()); 

但我一直收到一个“模糊调用”错误,我无法解决。

然后我试过了

 Mapper.CreateMap().ConvertUsing(x => new TypeOne()); 

并且使用无参数构造函数成功创建了TypeOne对象,但之后无法设置私有setter属性。

我已经在AutoMapper网站上寻求帮助并下载了源代码以获得良好的外观但是没有得到很少的文档,并且没有很多针对ConstructUsing的unit testing。

有什么明显的我错过了我应该用v2.1改变吗? 我很惊讶它从v1.1发生了很大的变化。

你只需要添加显式强制转换

 Func 

这是代码:

 Mapper.CreateMap().ConstructUsing( (Func) (r => new TypeOne())); 

当前版本的AutoMapper的工作原理如下:

  1. 按参数计数对目标类型构造函数进行排序

     destTypeInfo.GetConstructors().OrderByDescending(ci => ci.GetParameters().Length); 
  2. 获取第一个构造函数,其中哪些参数与源属性匹配(不检查空值)。 在您的情况下,它是具有两个参数的构造函数。