温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

AOP之PostSharp2-OnMethodBoundaryAspect

发布时间:2020-05-13 21:20:12 来源:网络 阅读:618 作者:破狼 栏目:编程语言

在上一篇中我们了解了简单的OnExceptionAspectAOP面向方向切入,在第一节中我们将继续我们的PostSharp AOP系列的OnMethodBoundaryAspect方法行为的切入,这也是我们常用的AOP切入。

   OnMethodBoundaryAspect顾名思义其为对方法边界的切入,定义如下:

AOP之PostSharp2-OnMethodBoundaryAspect

在这里提供了四个方法边界点为我们切入。我们可以很轻松的对方法权限,执行时间,参数合法性等aspect。

aspect传入参数MethodExecutionArgs给我如下信息,同时还包括父类AdviceArgs的Instance属性,实例方法才有值,静态方法则为null,

AOP之PostSharp2-OnMethodBoundaryAspect

这里还需要说一下属性FlowBehavior:表示方法执行行为,是一个枚举变量:

AOP之PostSharp2-OnMethodBoundaryAspect

二:执行时间统计demo

下面我们实践一个方法执行时间统计demo:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using PostSharp.Aspects;  
  6.  
  7. namespace PostSharpDemo  
  8. {  
  9.     [Serializable]  
  10.     public class OnMethodBoundaryAspectDemoAttribute : OnMethodBoundaryAspect  
  11.     {  
  12.         public bool Enabled  
  13.         {  
  14.             get;  
  15.             set;  
  16.         }  
  17.  
  18.         public override void OnEntry(MethodExecutionArgs args)  
  19.         {  
  20.             if (this.Enabled)  
  21.             {  
  22.                 args.MethodExecutionTag = System.Diagnostics.Stopwatch.StartNew();  
  23.             }  
  24.         }  
  25.         public override void OnExit(MethodExecutionArgs args)  
  26.         {  
  27.             if (this.Enabled)  
  28.             {  
  29.                 var sw = args.MethodExecutionTag as System.Diagnostics.Stopwatch;  
  30.                 if (sw != null)  
  31.                 {  
  32.                     sw.Stop();  
  33.                     Console.WriteLine(String.Format("方法{0}执行时间为:{1}s", args.Method.Name, sw.ElapsedMilliseconds / 1000));  
  34.                     sw = null;  
  35.                 }  
  36.             }  
  37.         }  
  38.     }  
  39. }  
测试方法:
 
  1. [OnMethodBoundaryAspectDemoAttribute(Enabled=true)]   
  2.        public static void OnMethodBoundaryAspectDemoAttributeTest()   
  3.        {   
  4.            System.Threading.Thread.Sleep(2000);   
  5.        } 

结果如下:

AOP之PostSharp2-OnMethodBoundaryAspect

注:这里我们也可以用到我们上节说的 多播(Multicasting)加到我们的class,assembly上统计我们所有的方法。

在最后在废话一句,我们可以很轻松的指定我们的方法(比如使我们的wcf服务操作契约)的访问权限,比如基于操作权限的功能点function的处理,如[PowerAttribute(“Add,Edit”)]这样简单处理,我们只需要在OnEnter中aspect,决定方法FlowBehavior行为,剩下的事情教给大家自己实践。

   欢迎大家积极指正和多多交流。

附件:demo下载

其他AOP参考:

  • AOP之PostSharp初见-OnExceptionAspect
  • AOP之PostSharp2-OnMethodBoundaryAspect
  • AOP之PostSharp3-MethodInterceptionAspect
  • AOP之PostSharp4-实现类INotifyPropertyChanged植入
  • AOP之PostSharp5-LocationInterceptionAspect
  • http://www.cnblogs.com/whitewolf/category/312638.html
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI