Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostSharp: Custom attributes are removed when using OnMethodInvocationAspect

Tags:

c#

aop

postsharp

I've got some aspect like this:

public class MyAttribute : OnMethodInvocationAspect
{
    public int Offset { get; internal set; }

    public MyAttribute(int offset)
    {
        this.Offset = offset;
    }

    public override void OnInvocation(MethodInvocationEventArgs eventArgs)
    {
         //do some stuff
    }
}

Now I'm having my class, and I add my attribute to it:

class MyClass
{
    [MyAttribute(0x10)]
    public int MyProp { get; set; }
}

Works all fine. Yet now I want to use reflection to get my offset; when I do

typeof(MyClass).GetProperty("MyProp").GetCustomAttributes(true);

It returns nothing. How can I access my original Offset value (the property on my attribute)?

like image 549
Jan Jongboom Avatar asked Oct 08 '09 18:10

Jan Jongboom


1 Answers

Ah, I fixed it this way:

First add an attribute to your attribute definition like:

[MulticastAttributeUsage(MulticastTargets.Method, PersistMetaData=true)]
public class MyAttribute : OnMethodInvocationAspect

And then I can call the get_ method of my property to get the data I want:

        foreach (PropertyInfo pi in typeof(T).GetProperties())
        {
            var entityAttribute = (MyAttribute)(typeof(T).GetMethod("get_" + pi.Name).GetCustomAttributes(typeof(MyAttribute), true).FirstOrDefault());
        }
like image 60
Jan Jongboom Avatar answered Oct 14 '22 20:10

Jan Jongboom