Castle DynamicProxy动态生成透明代理类型,实体不需要继承MarshalByRef、ContextBoundObject便可以实现代理类
基于透明代理的功能,可以实现对方法调用的拦截处理,例如NHibernate用它实现延迟加载
DP的使用非常简单,内部没有使用反射,而是采用Emit、委托等方式生成代理类型,调用真实类的方法,性能方面也没有太多损失
基本示例
引用的命名空间:
using Castle.Core.Interceptor;
using Castle.DynamicProxy;
public class SimpleSamepleEntity
{
public virtual string Name { get; set; }
public virtual int Age { get; set; }
public override string ToString()
{
return string.Format("{{ Name: \"{0}\", Age: {1} }}", this.Name, this.Age);
}
}
public class CallingLogInterceptor : IInterceptor
{
private int _indent = 0;
private void PreProceed(IInvocation invocation)
{
if (this._indent > 0)
Console.Write(" ".PadRight(this._indent * 4, ' '));
this._indent++;
Console.Write("Intercepting: " + invocation.Method.Name + "(");
if (invocation.Arguments != null && invocation.Arguments.Length > 0)
for (int i = 0; i < invocation.Arguments.Length; i++)
{
if (i != 0) Console.Write(", ");
Console.Write(invocation.Arguments == null
? "null"
: invocation.Arguments.GetType() == typeof(string)
? "\"" + invocation.Arguments.ToString() + "\""
: invocation.Arguments.ToString());
}
Console.WriteLine(")");
}
private void PostProceed(IInvocation invocation)
{
this._indent--;
}
public void Intercept(IInvocation invocation)
{
this.PreProceed(invocation);
invocation.Proceed();
this.PostProceed(invocation);
}
}
ProxyGenerator generator = new ProxyGenerator();
CallingLogInterceptor interceptor = new CallingLogInterceptor();
SimpleSamepleEntity entity = generator.CreateClassProxy<SimpleSamepleEntity>(interceptor);
entity.Name = "Richie";
entity.Age = 50;
Console.WriteLine("The entity is: " + entity);
Console.WriteLine("Type of the entity: " + entity.GetType().FullName);
Console.ReadKey();