DispatchProxy实现动态代理及AOP
DispatchProxy类是DotnetCore下的动态代理的类,源码地址:Github,官方文档:MSDN。主要是Activator以及AssemblyBuilder来实现的(请看源码分析),园子里的蒋老大提供的AOP框架Dora的实现也是大量使用了这两个,不过DispatchProxy的实现更简单点。
AOP实现:
#region 动态代理 dispatchproxy aop示例
class GenericDecorator : DispatchProxy
{
public object Wrapped { get; set; }
public Action<MethodInfo, object[]> Start { get; set; }
public Action<MethodInfo, object[], object> End { get; set; }
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
Start(targetMethod, args);
object result = targetMethod.Invoke(Wrapped, args);
End(targetMethod, args, result);
return result;
}
}
interface IEcho
{
void Echo(string message);
string Method(string info);
}
class EchoImpl : IEcho
{
public void Echo(string message) => Console.WriteLine($"Echo参数:{message}");
public string Method(string info)
{
Console.WriteLine($"Method参数:{info}");
return info;
}
}
#endregion
调用:
static void EchoProxy()
{
var toWrap = new EchoImpl();
var decorator = DispatchProxy.Create<IEcho, GenericDecorator>();
((GenericDecorator)decorator).Wrapped = toWrap;
((GenericDecorator)decorator).Start = (tm, a) => Console.WriteLine($"{tm.Name}({string.Join(',', a)})方法开始调用");
((GenericDecorator)decorator).End = (tm, a, r) => Console.WriteLine($"{tm.Name}({string.Join(',', a)})方法结束调用,返回结果{r}");
decorator.Echo("Echo");
decorator.Method("Method");
}
DispatchProxy是一个抽象类,我们自定义一个派生自该类的类,通过Create方法建立代理类与代理接口的依赖即可。结果: