DispatchProxy實現動態代理及AOP

DispatchProxy類是DotnetCore下的動態代理的類,源碼地址:Github,官方文檔:MSDN。主要是Activator以及AssemblyBuilder來實現的(請看源碼分析),園子裏的蔣老大提供的AOP框架Dora的實現也是大量使用了這兩個,不過DispatchProxy的實現更簡單點。html

AOP實現:git

#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

調用:github

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


首先,咱們要有三個概念:代理接口、委託類、代理類;分別對應着上面示例代碼裏面的IEcho、EchoImpl、GenericDecorator。咱們動態的建立一個派生自代理接口的代理類,同時封裝委託類的實例,那麼咱們調用代理類的方法實質上就是在調用內部的委託類的方法,所以咱們只須要在代理類的特定方法先後注入邏輯便可完成AOP操做。

這個思路也是上面提到的Dora框架中攔截器的思路。也是絕大數AOP框架實現的基本思路。app

相關文章
相關標籤/搜索