C# 方法拦截器

本文参考文章:https://www.cnblogs.com/lwhkdash/p/6728611.html
针对参考,写了一个方便的框架供大家使用:
github地址:https://github.com/lishuangquan1987/Tony.Interceptor
使用方法:

使用

1.定义一个类实现IInterceptor:

这样你就能处理方法调用前 BeforeInvoke 和方法调用后AfterInvoke

class LogInterceptor : IInterceptor
    {
        public void AfterInvoke(object result, MethodBase method)
        {
            Console.WriteLine($"执行{method.Name}完毕,返回值:{result}");
        }

        public void BeforeInvoke(MethodBase method)
        {
            Console.WriteLine($"准备执行{method.Name}方法");
        }
    }

2.在你想拦截的方法或者方法所属的类上面打标签

首先,你想拦截的方法所属的类必须继承自 ContextBoundObject

然后你必须用 InterceptorAttribute标签去修饰 实例 方法或者类

假如你的标签打在类上面,则默认拦截所有的公开实例方法

假如你不想拦截打了标签的类中的某个方法,你可以在方法上加上这个标签 InterceptorIgnoreAttribute,这样,它就不会被拦截

[Interceptor(typeof(LogInterceptor))]
    public class Test:ContextBoundObject
    {
        public void TestMethod()
        {
            Console.WriteLine("执行TestMethod方法");
        }
        public int Add(int a, int b)
        {
            Console.WriteLine("执行Add方法");
            return a + b;
        }
        [InterceptorIgnore]
        public void MethodNotIntercept()
        {
            Console.WriteLine("MethodNotIntercept");
        }
    }

3.创建类的实例并调用方法

class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        test.TestMethod();
        test.Add(5,6);
        test.MethodNotIntercept();
        Console.Read();
    }
}

本文所用的框架源码下载:https://github.com/lishuangquan1987/Tony.Interceptor

你可能感兴趣的:(C#,Aop,拦截器)