Custom Attributes not available in TypesMatch override

Nov 11, 2010 at 2:02 PM

Are custom attributes available in the values passed to the TypesMatch override in LoopValueInjection? 


I have a custom attribute on a String property, within a class I'm trying to inject from. When I perform my check in TypesMatch the sourceType does not return the custom attribute when queried.


For example, what I would like to work is: 


protected override bool TypesMatch(Type sourceType, Type targetType)


return targetType == typeof(string)

&& sourceType.GetCustomAttributes(typeof(CustomAttribute), true).Count() > 0;



Is this a bug, or am I going about it the wrong way? 


Thanks, Mark



Nov 11, 2010 at 2:34 PM
Edited Nov 11, 2010 at 2:36 PM


sourceType is System.String in your case, and of course it doesn't has your custom attribute applied

sourceType is just the type of the source property not the property itself

 here, I made a custom ValueInjection just for you, inherit it and in the TypesMatch use SourceAttributes and TargetAttributes (didn't tested it, but I think it should work)


using System;

using System.ComponentModel;

public class MarkLoopValueInjection : CustomizableValueInjection
        protected Type TargetPropType;
        protected Type SourcePropType;

        protected virtual bool UseSourceProp(string sourcePropName)
            return true;

        protected virtual string TargetPropName(string sourcePropName)
            return sourcePropName;

        protected AttributeCollection SourceAttributes;
        protected AttributeCollection TargetAttributes;

        protected override void Inject(object source, object target)
            var sourceProps = source.GetProps();
            for (var i = 0; i < sourceProps.Count; i++)
                var s = sourceProps[i];
                if (!UseSourceProp(s.Name)) continue;

                var t = target.GetProps().GetByName(SearchTargetName(TargetPropName(s.Name)));
                if (t == null) continue;

                SourceAttributes = s.Attributes;
                TargetAttributes = t.Attributes;

                if (!TypesMatch(s.PropertyType, t.PropertyType)) continue;
                TargetPropType = t.PropertyType;
                SourcePropType = s.PropertyType;
                var value = s.GetValue(source);
                if (AllowSetValue(value))
                    t.SetValue(target, SetValue(value));
Nov 11, 2010 at 3:07 PM

Ah, I didn't realise I could inherit from an Injection other than LoopValueInjection. That's exactly what I was after, thanks very much for the help.