AssertConfigurationIsValid(),当使用嵌套的ConstructUsing时,不忽略私有设置器

问题描述 投票:0回答:2

带有以下示例(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中进行各种组合,但到目前为止还没有运气。

我想这是一个静态分析挑战;我想知道我的构造函数涵盖了目标中的所有属性。我想知道,构造函数正在从源头传递所有内容。

我意识到,Automapper在这一点上还没有实现很多自动化,是否有一种很好的方法可以依靠automapper进行此测试,或者这是一个静态分析问题?

带有以下示例(LinqPad):void Main(){var config = new MapperConfiguration(cfg => {cfg.CreateMap

().ConstructUsing((...

c# automapper automapper-9
2个回答
0
投票
var config = new MapperConfiguration(cfg => { cfg.CreateMap<Source, DestinationNested>() .ForCtorParam("nestedValue", x => x.MapFrom(y => y.InnerValue)) .ForMember(x => x.NestedValue, x => x.MapFrom(y => y.InnerValue)); cfg.CreateMap<Source, DestinationOuter>() .ForPath(x => x.destinationNested.NestedValue, x => x.MapFrom(y => y.InnerValue)) .ForCtorParam("destinationNested", x => x.MapFrom(y => y)); });

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.