Question

Inside DynamicProxy Interceptor method I have:

public void Intercept(IInvocation invocation)
    {
        var _attribute = Attribute.GetCustomAttribute(invocation.Method, typeof(OneToManyAttribute), true);

I've decorated my property like this:

[OneToMany(typeof(Address), "IdUser")]
public virtual IList<Address> Addresses { get; set; }

_attribute is always null.

I think the problem is that invocation.Method is the automatic generated get_Addresses instead the decorated original property.

Is there a workaround to retrieve the attribute list in this situation?

Was it helpful?

Solution

You're correct - the invocation.Method will be the property accessor, not the property.

Here's a utility method to find the PropertyInfo corresponding to one of its accessor methods:

public static PropertyInfo PropertyInfoFromAccessor(MethodInfo accessor)
{
   PropertyInfo result = null;
   if (accessor != null && accessor.IsSpecialName)
   {
      string propertyName = accessor.Name;
      if (propertyName != null && propertyName.Length >= 5)
      {
         Type[] parameterTypes;
         Type returnType = accessor.ReturnType;
         ParameterInfo[] parameters = accessor.GetParameters();
         int parameterCount = (parameters == null ? 0 : parameters.Length);

         if (returnType == typeof(void))
         {
            if (parameterCount == 0)
            {
               returnType = null;
            }
            else
            {
               parameterCount--;
               returnType = parameters[parameterCount].ParameterType;
            }
         }

         if (returnType != null)
         {
            parameterTypes = new Type[parameterCount];
            for (int index = 0; index < parameterTypes.Length; index++)
            {
               parameterTypes[index] = parameters[index].ParameterType;
            }

            try
            {
               result = accessor.DeclaringType.GetProperty(
                  propertyName.Substring(4),
                  returnType,
                  parameterTypes);
            }
            catch (AmbiguousMatchException)
            {
            }
         }
      }
   }

   return result;
}

Using this method, your code would become:

var _attribute = Attribute.GetCustomAttribute(invocation.Method, typeof(OneToManyAttribute), true);
if (_attribute == null && invocation.Method.IsSpecialName)
{
   var property = PropertyInfoFromAccessor(invocation.Method);
   if (property != null)
   {
      _attribute = Attribute.GetCustomAttribute(property, typeof(OneToManyAttribute), true);
   }
}

If your OneToManyAttribute only applies to properties, not methods, you can omit the first call to GetCustomAttribute:

var property = PropertyInfoFromAccessor(invocation.Method);
var _attribute = (property == null) ? null : Attribute.GetCustomAttribute(property, typeof(OneToManyAttribute), true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top