10分钟入门AOP:用PostSharp普及一下AOP

PostSharp是一个比较强调易学易用的AOP框架,在这之前我接触过AspectJ,Spring.当然花的时间也不多,不过一直感觉不好掌握,似乎AOP是比较难的东西。今天看到这篇英文论文里面的说明,似乎并不那么难以掌握。参考下图,对比一下两组概念。


PS用了我们熟知的东西,而没有引入新名词,这是它聪明的地方。看表格右边的一组概念,事件(还不太理解为什么说是meta),事件处理器,aspect=定制的attribute, 唯一新鲜的是multicasting,实际上可以理解为一个通配表达式。

下面再用一个简单例子:

public class LogAttribute : OnMethodBoundaryAspect
{
public override void OnEntry (MethodExecutionEventArgs eventArgs )
{  Console . WriteLine (" Entering the method {0}." , eventArgs . Method );
}

public override void OnExit (MethodExecutionEventArgs eventArgs )
{
  Console . WriteLine (
" Leaving the method {0}." , eventArgs . Method );
}

}


class Program
{
[Log]
static void Main ()
{
    Console . WriteLine (" Hello , world .");
}
}

//multicasting 说明对
MyApp . BusinessObjects命名空间使用Log

[ assembly : Log(
AttributeTargetTypes =
" MyApp . BusinessObjects .*" ,
AttributeTargetMemberAttributes =
MulticastAttributes . Public )]

从这例子看非常简明清晰,的确易学易用。


posted @ 2008-03-22 16:18  分享  阅读(4736)  评论(4编辑  收藏  举报