2015-11-27 45 views
1

多播我有一个简单的方面:方面在postsharp

[System.Serializable()] 
[System.AttributeUsage(System.AttributeTargets.Assembly)] 
[PostSharp.Extensibility.MulticastAttributeUsage(PostSharp.Extensibility.MulticastTargets.Method)] 
public class NullableMethodCallAspect : PostSharp.Aspects.MethodInterceptionAspect 
{ 

    public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args) 
    { 
     if (args.Instance != null) 
      args.Proceed(); 
    } 

} 

我有我的解决方案中的两个项目:UIUIAppearanceExtensibility(这是由UI引用)。

在第二个中,我声明了一些接口,以便其他开发人员可以使用它们根据这些接口创建多个实现。

UI我宣布这些接口的属性,例如IInterface1

所以,从我的UI项目(组装),我需要我的方面适用于每次调用IInterface1对象...

我已经试过了,但是,它不工作:

[assembly: UI.Aspects.NullableMethodCallAspect(
    AttributeTargetAssemblies = "UIAppearanceExtensibility", 
    AttributeTargetTypes = "UI.Appearance.Extensibility.Triage.*", 
    AttributeTargetMembers = "regex: handle*" 
)] 

回答

1

在显示的例子中,接口成员的调用将在UI程序集中截获,但只有当它们通过接口类型的变量被访问时。

例如:

// Interface in UIAppearanceExtensibility 
public interface IInterface1 
{ 
    void Method1(); 
} 

// Class in UI 
public class Class1 : IInterface1 
{ 
    // ... 
} 

// This usage in UI will be intercepted 
IInterface1 i1 = new Class1(); 
i1.Method1(); 

// This usage in UI will not be intercepted 
Class1 c1 = new Class1(); 
c1.Method1(); 

的原因是,在第二种情况下由编译器生成的IL代码不引用IInterface1和应用方面,当PostSharp正在寻找的IInterface1惯例。

就你的情况而言,将方面应用于UIAppearanceExtensibility程序集本身的接口可能更好,并将AttributeInheritance属性设置为MulticastInheritance.Strict。然后该属性将被组播到实现该接口的类。该使用案例记录在Understanding Aspect Inheritance中。

// In the UIAppearanceExtensibility project 
[assembly: UI.Aspects.NullableMethodCallAspect(
    AttributeInheritance = MulticastInheritance.Strict 
    AttributeTargetTypes = "UI.Appearance.Extensibility.Triage.*", 
    AttributeTargetMembers = "regex: handle*" 
)]