Can I apply an aspect to all public methods in an assembly with a specific return type?

StackOverflow https://stackoverflow.com/questions/20649356

  •  19-09-2022
  •  | 
  •  

Question

I'd like to apply an aspect to all public methods in an assembly who have the return type of ActionResult.

I'm thinking something like:

[assembly: MyActionAspect(AttributeTargetMemberAttributes = MulticastAttributes.Public, AttributeTargetTypes = "ActionResult")]

But it doesn't seem to work...

Était-ce utile?

La solution

In your example you set AttributeTargetTypes = "ActionResult", but AttributeTargetTypes is not related to the return type of the method. It allows you to filter types on which to apply the aspect. So, you would set it to the full name of the ActionResult type if you wanted to apply the aspect inside the ActionResult class (you can also use wildcards and regex in this property).

However, to filter methods on return type you need to take a different approach.

The first option is to override CompileTimeValidate in your aspect and return false for methods that you want to filter out:

public override bool CompileTimeValidate(MethodBase method)
{
    MethodInfo methodInfo = method as MethodInfo;
    return methodInfo != null && methodInfo.ReturnType == typeof (ActionResult);
}

The second option is to create another attribute and implement IAspectProvider. This is a bit more laborious, but allows you to add aspects dynamically to your code and to implement more complex scenarios.

[MulticastAttributeUsage(MulticastTargets.Method)]
public class MyAspectProvider : MulticastAttribute, IAspectProvider
{
    public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
    {
        MethodInfo methodInfo = (MethodInfo) targetElement;
        if (methodInfo.ReturnType == typeof (ActionResult))
        {
            return new[] {new AspectInstance(targetElement, new MyActionAspect())};
        }

        return new AspectInstance[0];
    }
}

// apply to assembly:
[assembly: MyAspectProvider(AttributeTargetMemberAttributes = MulticastAttributes.Public)]

You can read more about IAspectProvider on this doc page.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top