.NET Core 实现动态代理 AOP


AOP实现

class DynamicProxy : DispatchProxy
{
    public T? decorated { get; set; }//目标类  
    public Action? _beforeAction { get; set; }  // 动作之后执行  
    public Action? _afterAction { get; set; } // 动作之前执行

    protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
    {
        Exception exception = null;

        BeforeAction(args);
        object result = null;
        try
        {
            //调用实际目标对象的方法  
            result = targetMethod?.Invoke(decorated, args);
        }
        catch (Exception ex)
        {
            exception = ex;
        }
        AfterAction(args, result);
        //调用完执行方法后的委托,如果有异常,抛出异常  
        if (exception != null)
        {
            throw exception;
        }
        return result;
    }

    ///   
    /// 创建代理实例  
    ///   
    /// 代理的接口类型  
    /// 方法执行前执行的事件  
    /// 方法执行后执行的事件  
    ///   
    public T Create(T decorated, Action beforeAction, Action afterAction)
    {
        object proxy = Create>(); // 调用DispatchProxy 的Create  创建一个新的T  
        DynamicProxy proxyDecorator = (DynamicProxy)proxy;
        proxyDecorator.decorated = decorated;
        //把自定义的方法委托给代理类  
        proxyDecorator._beforeAction = beforeAction;
        proxyDecorator._afterAction = afterAction;
        return (T)proxy;
    }


    private void BeforeAction(object?[]? args)
    {
        try
        {
            _beforeAction.Invoke(args);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"执行之前异常:{ex.Message},{ex.StackTrace}");
        }
    }

    private void AfterAction(object?[]? args, object? result)
    {
        try
        {
            _afterAction.Invoke(args, result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"执行之后异常:{ex.Message},{ex.StackTrace}");
        }
    }
}

interface IInterceptor
{
    ///   
    /// 执行之前  
    ///   
    /// 参数  
    void BeforeAction(object?[]? args);

    ///   
    /// 执行之后  
    ///   
    /// 参数  
    /// 结果  
    void AfterAction(object?[]? args, object result);
}

[AttributeUsage(AttributeTargets.Class)]
class InterceptAttribute : Attribute
{
    public Type Type { get; set; }
    public InterceptAttribute(Type type)
    {
        this.Type = type;
    }
}

class ProxyFactory
{
    ///   
    /// 创建代理实例  
    ///   
    /// 代理的接口类型  
    ///   
    public static T Create()
    {
        T decorated = ServiceHelper.GetService();
        Type type = decorated.GetType();
        InterceptAttribute attrib = type.GetCustomAttribute();
        IInterceptor interceptor = ServiceHelper.GetService(attrib.Type);

        //创建代理类  
        return new DynamicProxy().Create(decorated, interceptor.BeforeAction, interceptor.AfterAction);
    }
}

static class ServiceHelper
{
    public static IServiceProvider? serviceProvider { get; set; }

    public static void BuildServiceProvider(IServiceCollection serviceCollection)
    {
        //构建容器  
        serviceProvider = serviceCollection.BuildServiceProvider();
    }

    public static T GetService(Type serviceType)
    {
        return (T)serviceProvider.GetService(serviceType);
    }

    public static T GetService()
    {
        return serviceProvider.GetService();
    }
}

AOP使用

class AOPTest : IInterceptor
{
    void IInterceptor.BeforeAction(object[] args)
    {
        Console.WriteLine($"AOP方法执行之前,args:{args}");
        //throw new Exception("异常测试(异常,但依然不能影响程序执行)");
    }
     void IInterceptor.AfterAction(object[] args, object result)
    {
        Console.WriteLine($"AOP方法执行之后,args:{args},result:{result}");
    }
}

interface ITestService
{
    public int Add(int a, int b);
}

[Intercept(typeof(AOPTest))]
class TestService : ITestService
{
    int ITestService.Add(int a, int b)
    {
        Console.WriteLine($"正在执行--》Add({a},{b})");

        //throw new Exception("方法执行--》测试异常");
        return a + b;
    }
}

测试

    IServiceCollection = new ServiceCollection();
    serviceCollection.AddTransient(typeof(AOPTest));
    serviceCollection.AddTransient();
    //构建容器  
    ServiceHelper.BuildServiceProvider(serviceCollection);

    //用工厂获取代理实例  
    var s = ProxyFactory.Create();
    var sum = s.Add(1, 2);
    Console.WriteLine("执行完毕=====>" + sum);

测试输出

AOP方法执行之前,args:System.Object[]
正在执行--》Add(1,2)
AOP方法执行之后,args:System.Object[],result:3
执行完毕=====>3

转自:极客Bob
链接:cnblogs.com/Bob-luo/p/15716592.html

Aop