带你学习AOP框架之Aspect.Core[1]

  在软件业,AOP为Aspect Oriented Programming的缩写,意为:

这AspectCore中需要创建一个拦截器一般继承自 AbstractInterceptorAttribute。并且实现它的 Invoke 方法 。

其中第一个参数是上下文,next是执行的委托方法,通过这个委托可以执行被拦截的方法。

复制代码
//每个被拦截的方法中执行        public async override Task Invoke(AspectContext context, AspectDelegate next)         {             try             {                 Console.WriteLine("Before service call");                 await next(context);            }             catch (Exception)             {                 Console.WriteLine("Service threw an exception!");                 throw;             }             finally             {                 Console.WriteLine("After service call");             }         }
复制代码

首先我们可以创建一个需要被代理拦截的类(必须是public方法是虚方法且被标记,也必须使用MVC中的Filter命名规范)。这个方法也可以是异步的!

复制代码
public class Person {     [CustomInterceptor]     public virtual void Say(string msg)     {         Console.WriteLine("service calling..."+msg);     } }    
复制代码

 如何进行代理? 需要通过ProxyGeneratorBuilder 来代理对象,注意 p 指向的对象是 AspectCore 生成的 Person 的动态子类的对象,直接 new Person是无法被拦截的。

复制代码
static void Main(string[] args)         {             ProxyGeneratorBuilder proxyGeneratorBuilder = new ProxyGeneratorBuilder();             using (IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build())             {                 Person p = proxyGenerator.CreateClassProxy<Person>();                 p.Say("zaranet");             }         }
复制代码

 上面说到我们不可以直接new这个person,那现在我们调试一下,一探究竟!!!我们看看这个p是个什么类型。

噫?为什么这个p不是AspectPollyIdn.Person?而是AspectCore.DynamicGenerated.Person?不妨把这个p的父类给打印出来,来瞅瞅。

复制代码
static void Main(string[] args)         {             ProxyGeneratorBuilder proxyGeneratorBuilder = new ProxyGeneratorBuilder();             using (IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build())             {                 Person p = proxyGenerator.CreateClassProxy<Person>();                 Console.WriteLine(p.GetType().BaseType);                 p.Say("zaranet");             }         }
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信