通过执行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);
}
}
}
}
请注意,这不包括从被调用方法等调用的方法的日志记录。我的理解是,你想记录从目标方法直接调用的方法。