如何使用ValueInjecter控制去模糊的深度

本文关键字:深度 去模糊 控制 何使用 ValueInjecter | 更新日期: 2023-09-27 18:24:22

我确信这个解决方案非常明显,但我对如何使用值注入器执行以下操作有什么想法吗?

假设您有以下型号:

public class Foo{
    public int BarId{get;set;}
    public Bar Bar{get;set;}
}
public class Bar{
    public int Id{get;set;}
    [Required]
    public string Description{get;set;}
}

和一个看起来像这样的视图模型:

public class FooBarViewModel{
    public int BarId{get;set;}
    public bool EditMode{get;set;}
}

当我在Foo对象上调用InjectFrom<UnflatLoopValueInjection>()时,我只希望填充Foo.BarId属性,而不是Foo.Bar.Id属性。如果可能的话,如果在图中较浅的深度发现与属性名称完全匹配,我希望停止"取消限制"过程在整个对象图中递归。

理想情况下,我希望这样做,而不需要明确地忽略属性,并且能够按照惯例这样做。

如何使用ValueInjecter控制去模糊的深度

深入研究源代码后,我怀疑实现是微不足道的

public class UnflatLoopValueInjectionUseExactMatchIfPresent : UnflatLoopValueInjection {
    protected override void Inject(object source, object target) {
        var targetProperties = target.GetProps().Cast<PropertyDescriptor>().AsQueryable();
        foreach (PropertyDescriptor sourceProp in source.GetProps()) {
            var prop = sourceProp;
            if (targetProperties.Any(p => p.Name == prop.Name)) {
                //Exact match found
                targetProperties.First(p => p.Name == prop.Name).SetValue(target, SetValue(sourceProp.GetValue(source)));
            }
            else {
                //Fall back to UnflatLoopValueInjection
                var endpoints = UberFlatter.Unflat(sourceProp.Name, target, t => TypesMatch(prop.PropertyType, t)).ToList();
                if (!endpoints.Any()) {
                    continue;
                }
                var value = sourceProp.GetValue(source);
                if (!AllowSetValue(value)) {
                    continue;
                }
                foreach (var endpoint in endpoints) {
                    endpoint.Property.SetValue(endpoint.Component, SetValue(value));
                }
            }
        }
    }
}

只有在找不到与viewmodels属性名称完全匹配的情况下,上述注入才会深入(使用标准UnflatLoopValueInjection中的逻辑)到对象图中。