2017-02-24 45 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); 
      } 
     } 
    } 
} 

请注意,这不包括从被调用方法等调用的方法的日志记录。我的理解是,你想记录从目标方法直接调用的方法。

相关问题