Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostSharp How to know at runtime if a certain aspect was applied to a method?

I'm implementing a PostSharp aspect library and can't find out a solution to the following problem.

Suppose we have an aspect that will be applied for some methods and won't be applied for the others. I need some mechanism that I can use at runtime to know whether an aspect was applied to a method. Specifically, what is the recommended way to determine at runtime whether certain aspect was applied to a particular method given by a System.Reflection.MethodBase?

The first solution that comes into my head is to make PostSharp mark every method that has been modified by this aspect with a custom atribute and use methodBase.CustomAttributes at runtime. Is this the right solution for the problem? Or maybe there already is a ready-to-use or more elegant solution in PostSharp.

Also, please take into account that preferred is a solution that doesn't require a paid PostSharp license since Free Community Edition is enough for my current project. Anyway, it would be very intresting to discuss solutions based on paid PostSharp functionality too.

like image 903
Alexander Abakumov Avatar asked Dec 29 '14 17:12

Alexander Abakumov


1 Answers

When you're adding a method-level aspect (e.g. OnExceptionAspect) as an attribute on the class or the assembly level, PostSharp multicasts this attribute to all the applicable methods in that class/assembly. At the next stage the aspect transforms each method with the attribute and the attribute itself is removed.

You can tell PostSharp to keep all the aspect attributes by setting the MulticastAttributeUsageAttribute.PersistMetaData property to true. The [MulticastAttributeUsage] attribute must be applied to your aspect class.

[MulticastAttributeUsage( PersistMetaData = true )]
public class MyAspect : OnExceptionAspect
{
    // ...
}

Now you can look for MyAspect in MethodBase.CustomAttributes to determine whether the aspect has been applied to the current method.

like image 156
AlexD Avatar answered Sep 21 '22 22:09

AlexD