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方法建立代理類與代理接口的依賴即可。結果: