仅将方面应用于具有特定属性的方法

Fab*_*amp 6 c# aop postsharp

我正在尝试设置PostSharp方面,RunOutOfProcessAttribute以便它适用于:

  1. 所有公共方法
  2. DoSpecialFunctionAttribute无论成员可访问性如何(public/protected/private/whatever),标记为的任何方法.

到目前为止,我RunOutOfProcessAttribute的定义如下:

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Public)]
[AttributeUsage(AttributeTargets.Class)]
public class RunOutOfProcessAttribute : MethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

MulticastAttributeUsageAttribute已经到位的应履行标准1以上,但我还是不知道如何履行标准2,没有简单地复制现有方面的行为变成一个新的属性.

DoSpecialFunctionAttribute无论成员的可访问性如何(public/protected/private/whatever),我如何将此方面应用于标有该方法的任何方法?

Fab*_*amp 6

这是解决方案:

  • 用所有方法定位 [MulticastAttributeUsage(MulticastTargets.Method)]
  • 覆盖CompileTimeValidate(MethodBase method).设置返回值,使得在适当的目标上CompileTimeValidate返回true,false在目标上静默忽略,并在应警告用户Aspect使用不合适时抛出异常(这在PostSharp文档中有详细说明).

在代码中:

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method)]
[AttributeUsage(AttributeTargets.Class)]
public class RunOutOfProcessAttribute : MethodInterceptionAspect
{
    protected static bool IsOutOfProcess;

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        ...
    }

    public override bool CompileTimeValidate(MethodBase method)
    {
        if (method.DeclaringType.GetInterface("IDisposable") == null)
            throw new InvalidAnnotationException("Class must implement IDisposable " + method.DeclaringType);

        if (!method.Attributes.HasFlag(MethodAttributes.Public) && //if method is not public
            !MethodMarkedWith(method,typeof(InitializerAttribute))) //method is not initialiser
            return false; //silently ignore.

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)