代码改变世界

AOP之PostSharp2-OnMethodBoundaryAspect

2011-12-04 19:03  破狼  阅读(4490)  评论(4编辑  收藏  举报

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

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

SNAGHTML20c8c71

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

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

image

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

image

二:执行时间统计demo

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PostSharp.Aspects;

namespace PostSharpDemo
{
    [Serializable]
    public class OnMethodBoundaryAspectDemoAttribute : OnMethodBoundaryAspect
    {
        public bool Enabled
        {
            get;
            set;
        }

        public override void OnEntry(MethodExecutionArgs args)
        {
            if (this.Enabled)
            {
                args.MethodExecutionTag = System.Diagnostics.Stopwatch.StartNew();
            }
        }
        public override void OnExit(MethodExecutionArgs args)
        {
            if (this.Enabled)
            {
                var sw = args.MethodExecutionTag as System.Diagnostics.Stopwatch;
                if (sw != null)
                {
                    sw.Stop();
                    Console.WriteLine(String.Format("方法{0}执行时间为:{1}s", args.Method.Name, sw.ElapsedMilliseconds / 1000));
                    sw = null;
                }
            }
        }
    }
}

测试方法:

[OnMethodBoundaryAspectDemoAttribute(Enabled=true)] 
       public static void OnMethodBoundaryAspectDemoAttributeTest() 
       { 
           System.Threading.Thread.Sleep(2000); 
       }

结果如下:

image

注:这里我们也可以用到我们上节说的 多播(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