如何在 ValueInjecter 3.1 中指定自定义匹配规则?

How to specify custom match rules in ValueInjecter 3.1?

在旧版本的 ValueInjecter(版本 2.3)中,我创建了 classes 扩展 ConventionInjection 以控制匹配的属性 - 这使我能够做这样的事情:

    public class UnderscoreInjector : ConventionInjection
{
    protected override bool Match(ConventionInfo c)
    {
        return c.SourceProp.Type == c.TargetProp.Type
            && c.SourceProp.Name.Replace("_", "") == c.TargetProp.NameReplace("_", "");
    }
}

忽略名称中的下划线(当您必须处理一些旧的、名称奇怪的业务对象并且不想让这些奇怪的名称冒泡到您的核心代码中时很有用)

在最新的3.1版本中我只能通过subclassing LoopInjection or PropertyInjection来自定义类型的匹配classes:

        protected override bool MatchTypes(Type source, Type target)
    {
        return source == typeof(int) && target.IsSubclassOf(typeof(Enum));
    }

在这些 classes 中,如果我想更改属性名称的映射方式,似乎没有任何明显的覆盖点。

我看到在3.1中我们可以为特定字段定义自定义映射:

    Mapper.AddMap<Customer, CustomerInput>(src =>
{
    var res = new CustomerInput();
    res.InjectFrom(src); // maps properties with same name and type
    res.FullName = src.FirstName + " " + src.LastName;
    return res;
});

但这不是基于约定的,因此您必须手动调整所有不理想的字段

ConventionInjection class 发生了什么?它刚刚被重命名还是有不同的方法来在最新版本中创建这些类型的自定义映射?

使用循环注入 你可以覆盖 string GetTargetProp(string sourceName) 这意味着让 sourcePropName 确定 targetPropName 因此,如果源代码包含下划线而目标代码不包含下划线,您可以这样做:

  protected override string GetTargetProp(string sourceName)
  {
     return sourceName.Replace("-", string.Empty);                   
  }

ConventionInjection 的工作方式不同,它循环遍历所有可能的匹配项并执行匹配函数,这要慢得多。

但是,如果 LoopInjection 方案不适合您,您可以恢复 ConventionInjection,只需从此处复制它:http://valueinjecter.codeplex.com/SourceControl/latest#ValueInjecter/ConventionInjection.cs 到您的解决方案中