2015-11-27 43 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*" 
)]