2017-02-24 104 views
0

我最近開始爲我們的項目之一使用PostSharp。目標是對於在特定方法(代表特定功能)內調用的所有方法的日誌方法執行時間。如何爲特定方法中調用的所有方法啓用PostSharp?

我到目前爲止所做的是我創建了一個方面(比如說TimingAspect),並在一個方法上測試了它(通過在方法定義上面寫'[TimingAspect]')。它工作正常,在單獨的日誌文件中記錄該方法的執行時間。根據我的知識,如果我在方法定義之上編寫'[TimingAspect]',它只記錄該方法,而不記錄從該方法調用的其他方法。我對嗎 ?所以現在我想知道是否有什麼辦法可以實現目標,即對於在特定方法中被調用的所有方法的日誌方法執行時間

回答

0

通過執行IAspectProvider,您可以將您的方面應用於從目標方法調用的方法。要查找所有調用的方法,您可以使用PostSharp API中的ReflectionSearch類。

下面你可以找到這樣的方面提供者的例子。

[PSerializable] 
public class TimingAspectProvider : MethodLevelAspect, IAspectProvider 
{ 
    public IEnumerable<AspectInstance> ProvideAspects(object targetElement) 
    { 
     MethodBase targetMethod = (MethodBase) targetElement; 

     IAspectRepositoryService aspectRepositoryService = PostSharpEnvironment.CurrentProject.GetService<IAspectRepositoryService>(); 
     TimingAspect aspect = new TimingAspect(); 

     MethodUsageCodeReference[] usages = ReflectionSearch.GetDeclarationsUsedByMethod(targetMethod); 
     foreach (MethodUsageCodeReference codeReference in usages.Where(u => u.UsedDeclaration.MemberType == MemberTypes.Method)) 
     { 
      if (!aspectRepositoryService.HasAspect(codeReference.UsedDeclaration, typeof(TimingAspect))) 
      { 
       yield return new AspectInstance(codeReference.UsedDeclaration, aspect); 
      } 
     } 
    } 
} 

請注意,這不包括從被調用方法等調用的方法的日誌記錄。我的理解是,你想記錄從目標方法直接調用的方法。

相關問題