Rob West
Rob West

Reputation: 5241

Access custom attribute on method from Castle Windsor interceptor

I am trying to access a custom attribute applied to a method within a castle interceptor, e.g.:

[MyCustomAttribute(SomeParam = "attributeValue")]
public virtual MyEntity Entity { get; set; }

using the following code:

internal class MyInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method.GetCustomAttributes(typeof(MyCustomAttribute), true) != null)
        {
            //Do something
        }
    }
}

The interceptor is firing OK when the method is called but this code does not return the custom attribute. How can I achieve this?

Upvotes: 4

Views: 2412

Answers (3)

VahidN
VahidN

Reputation: 19156

Try

private static Attribute getMyCustomAttribute(IInvocation invocation)
{
   var methodInfo = invocation.MethodInvocationTarget;
   if (methodInfo == null)
   {
      methodInfo = invocation.Method;
   }
   return Attribute.GetCustomAttribute(methodInfo, typeof(MyCustomAttribute), true);
}

Upvotes: 3

Rob West
Rob West

Reputation: 5241

I think I've figured it out - it is because of the difference between the property and the method. It is the get_ method that triggers the interceptor, and this is not decorated with the attribute of the parent property.

Upvotes: 1

Krzysztof Kozmic
Krzysztof Kozmic

Reputation: 27374

Try Attribute.GetCustomAttribute(...) static method for this. It's bizarre but these two methods return different results sometimes for some strange reason.

Upvotes: 4

Related Questions