Search code examples
c#valueinjecter

How to specify custom match rules in ValueInjecter 3.1?


In older version of ValueInjecter (Version 2.3) I created classes that extended ConventionInjection in order to control which properties matched - this enabled me to do thing like:

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

to ignore underscores in the names (useful when you have to deal with some old, oddly named business objects and don't want to let the strange names bubble up into your core code)

In the latest version 3.1 I can only find a way to customize the matching of the type by subclassing LoopInjection or PropertyInjection classes:

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

In these classes there doesn't seem to be any obvious point to override if I want to change the way the names of properties are mapped.

I can see that in 3.1 we can define custom maps for specific fields:

    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;
});

but this isn't convention based and so you'd have to hand-crank all of the fields which isn't ideal

What happened to the ConventionInjection class? Has it just been renamed or is there a different way to create these types of custom mappings in the latest version?


Solution

  • using LoopInjection you can override string GetTargetProp(string sourceName) this means that having the sourcePropName determine the targetPropName so if the source contains underlines and the target doesn't you could do this:

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

    the ConventionInjection worked differently it was looping through all the possible matches and executing the matching functions, which was much slower.

    however if the LoopInjection scenario doesn't work for you could bring back the ConventionInjection, just copy it from here: http://valueinjecter.codeplex.com/SourceControl/latest#ValueInjecter/ConventionInjection.cs into your solution