使用以下示例(LinqPad):
void Main()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, DestinationNested>()
.ConstructUsing((source, context) => new DestinationNested(source.InnerValue));
cfg.CreateMap<Source, DestinationOuter>()
.ForMember(x => x.OuterValue, y => y.MapFrom(z => z.OuterValue))
.ConstructUsing((source, context) =>
{
return new DestinationOuter(source.OuterValue, context.Mapper.Map<DestinationNested>(source));
});
});
var src = new Source { OuterValue = 999, InnerValue = 111 };
var mapper = config.CreateMapper();
var mapped = mapper.Map<DestinationOuter>(src);
mapped.Dump();
mapper.ConfigurationProvider.AssertConfigurationIsValid();
}
public class Source
{
public int OuterValue { get; set; }
public int InnerValue { get; set; }
}
public class DestinationOuter
{
public int OuterValue { get; private set; }
public DestinationNested destinationNested { get; private set; }
public DestinationOuter(int outerValue, DestinationNested destinationNested)
{
this.OuterValue = outerValue;
this.destinationNested = destinationNested;
}
}
public class DestinationNested
{
public int NestedValue { get; private set; }
public DestinationNested(int nestedValue)
{
this.NestedValue = nestedValue;
}
}
AssertConfigurationIsValid() 当前在我使用 ContructUsing 时引发有关属性的异常。
实际上它确实映射正确,但我希望 AssertConfigurationIsValid 作为我的测试套件的一部分来查找回归(无需对映射器进行手动测试)。
我想保证我的所有属性都通过构造函数从源映射到目标。我希望使用一个构造器,因为它是我的域层,并且构造器强制执行强制性项目。
我不希望通过 IgnoreAllPropertiesWithAnInaccessibleSetter() 功能忽略所有私有设置器,因为我可能会忽略一些我实际上没有设置的东西。
理想情况下,我也不想对出现在构造函数中的每个属性进行手动 Ignore() 操作,因为这会导致代码漂移。
我在 Automapper 中尝试了各种组合,但到目前为止还没有运气。
我想这是一个静态分析挑战;我想知道我的承包商涵盖了 Destination 中的所有属性。而且我想知道构造函数是从源头传递的。
我意识到 Automapper 在这一点上并不是很自动化,有没有一种很好的方法可以依靠 automapper 进行此测试,或者这是否是一个静态分析问题?