AOP之Castle DynamicProxy 动态代理

时间:2025-05-13 19:33:49

  这里主要介绍使用castle这个动态代理,在.net一些开源的框架里可以找到它的影子,就连微软的rchard也是使用这个进行方法拦截等可以基于这个进行方法拦截,在这个方面PostSharp算是比较好用的,可以跟使用属性一样使用没有代码侵入,可是这个是收费,postsharp使用的是运行时注入,这个在之前的文章已经说过这里不再重复说,这里就直接进入正题。

  这里介绍先DynamicProxy的方法拦截功能先来个例子

  先定义一个类

   public class MyClass : IMyClass
{
public virtual void MyMethod()
{
Console.WriteLine("My Mehod");
}
}

  virtual这个算是castle的一个标志,不管是方法或者是属性都要这个。应该在NHibernate里都见过了。这个就是要代理的类啦,接下来定义拦截器

  

public class TestIntercept : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("");
invocation.Proceed();
Console.WriteLine("");
}
}

这个就是拦截器啦进行方法拦截就靠这个了,这个也可以跟类一样使用有参构造,比如也可以这样子

  

 [Serializable]
public class TransactionWithRetries : IInterceptor
{
private readonly Int32 _maxRetries; public TransactionWithRetries(Int32 maxRetries)
{
_maxRetries = maxRetries;
} public void Intercept(IInvocation invocation)
{ Console.WriteLine("before22222");
var successed = false;
var retries = _maxRetries;
while (!successed)
{
using (var trans = new TransactionScope())
{
try
{
Console.WriteLine("before");
invocation.Proceed();
Console.WriteLine("End");
trans.Complete();
}
catch
{
if (retries >= )
{
Console.WriteLine("Retrying");
retries--;
}
else
{
throw;
}
}
}
} } }

这个时候可以传递参数进来,这个只是使用事务,至于权限以及日志什么的也类似写在方法拦截里就可以了

最后到了出结果的时候了

 

 var proxyGenerate = new ProxyGenerator();
TestIntercept t=new TestIntercept(); var pg = proxyGenerate.CreateClassProxy<MyClass>(t);
pg.MyMethod();

最后执行起来是这个样子的结果

  11111111

  My Mehod

  222

可以看到执行顺序是先进入拦截器里面,然后执行方法。下一篇写写IOC框架