DispatchProxy dynamic proxy class is under DotnetCore class, source address: Github , official documents: the MSDN . Mainly Activator and AssemblyBuilder to achieve, to achieve AOP framework Dora's garden Jiang boss also provided extensive use of these two, but DispatchProxy implementation more simple.
AOP implementations:
#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
transfer:
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 is an abstract class, we customize a class derived from the class, you can rely on the establishment of a proxy class and proxy interfaces by the Create method. result: