Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 588
Rob West Avatar asked Feb 27 '23 07:02

Rob West


2 Answers

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

like image 75
Krzysztof Kozmic Avatar answered Apr 26 '23 15:04

Krzysztof Kozmic


Try

private static Attribute getMyCustomAttribute(IInvocation invocation)
{
   var methodInfo = invocation.MethodInvocationTarget;
   if (methodInfo == null)
   {
      methodInfo = invocation.Method;
   }
   return Attribute.GetCustomAttribute(methodInfo, typeof(MyCustomAttribute), true);
}
like image 29
VahidN Avatar answered Apr 26 '23 17:04

VahidN