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

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

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

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

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

二:执行时间统计demo

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

usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingPostSharp.Aspects; namespacePostSharpDemo { [Serializable] publicclassOnMethodBoundaryAspectDemoAttribute:OnMethodBoundaryAspect { publicboolEnabled { get; set; } publicoverridevoidOnEntry(MethodExecutionArgsargs) { if(this.Enabled) { args.MethodExecutionTag=System.Diagnostics.Stopwatch.StartNew(); } } publicoverridevoidOnExit(MethodExecutionArgsargs) { if(this.Enabled) { varsw=args.MethodExecutionTagasSystem.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)] publicstaticvoidOnMethodBoundaryAspectDemoAttributeTest() { System.Threading.Thread.Sleep(2000); }

结果如下:

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