在上一篇使用.Net Remoting实现动态代理中,我们实现了对Student
的动态代理,现在我们用Castle
来实现同样的效果
先写一个人物接口
public interface IUserProcessor
{
string Name { get; set; }
int Age { get; set; }
void ShowMe();
}
然后写一个Worker
类实现该接口
/// <summary>
/// 这里与.Net Remoting不同
/// .Net Remoting需要同时继承MarshalByRefObject,否则无法动态生成
/// 而Castle需要把ShowMe写成虚方法,
/// </summary>
public class Worker : IUserProcessor
{
public string Name { get; set; }
public int Age { get; set; }
//这里必须是virtual,其本质就是重写该方法
public virtual void ShowMe()
{
Console.WriteLine(ToString());
}
public override string ToString()
{
return $"大家好,我是{Name},我几年{Age}岁了";
}
}
然后我们新建一个InterceptHelper
,继承IInterceptor
接口,需要引入Castle.core
using Castle.DynamicProxy;
public class InterceptHelper : IInterceptor
{
public void Intercept(IInvocation invocation)
{
//之前
DoSomethingBefore(invocation);
//调用
invocation.Proceed();
//之后
DoSomethinfAfter(invocation);
}
/// <summary>
/// 在方法执行前,做的一些事
/// </summary>
/// <param name="msg"></param>
private void DoSomethingBefore(IInvocation invocation)
{
Console.WriteLine("在方法执行前,做的一些事");
}
/// <summary>
/// 在方法执行后,做的一些事
/// </summary>
/// <param name="message"></param>
private void DoSomethinfAfter(IInvocation invocation)
{
Console.WriteLine("在方法执行后,做的一些事");
}
}
最后,这是代理生成的方法
InterceptorHelper interceptor = new InterceptorHelper();
IUserProcessor worker = new ProxyGenerator().CreateClassProxy<IUserProcessor>(interceptor);