通過執行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);
}
}
}
}
請注意,這不包括從被調用方法等調用的方法的日誌記錄。我的理解是,你想記錄從目標方法直接調用的方法。