PostSharp: Custom attributes are removed when using OnMethodInvocationAspect
Asked Answered
M

1

11

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)?

Mckoy answered 8/10, 2009 at 18:17 Comment(0)
M
16

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());
        }
Mckoy answered 8/10, 2009 at 18:28 Comment(1)
I've got a similar problem whereby attributes inherited from PostSharp related classes aren't there at runtime. Would like to understand the underlying mechanism here as to whyEssonite

© 2022 - 2024 — McMap. All rights reserved.