介绍:
AspectCore是.NET标准的基于AOP的跨平台框架【github解释】。主要支持:对方面拦截器,依赖注入集成,Web应用程序,数据验证等的核心支持。
使用实例:
首先安装dll:
Install-Package AspectCore.Core
引用完dll就可以使用了,我们来创建基本的处理类:ErrorCommandAttribute
介绍就不说了,理论我也知道的不多,直接上代码:
class ErrorCommandAttribute : AbstractInterceptorAttribute { string _mess; public ErrorCommandAttribute(string methon) { _mess = methon; } /// <summary> /// 每个被拦截的方法中执行 /// </summary> /// <param name="context"></param> /// <param name="next"></param> /// <returns></returns> public override async Task Invoke(AspectContext context, AspectDelegate next) { try { Console.WriteLine("AddAsync方法开始前"); await next(context); // 执行被拦截的方法 } catch (Exception) { Console.WriteLine("AddAsync方法出错"); try { //Type[] mytypes = Assembly.GetExecutingAssembly().GetTypes(); Type type= typeof(User);//user 是类 var methom = Activator.CreateInstance(type);//反射创建类 MethodInfo methodinfo = type.GetMethod(_mess);//获取方法 _mess参数是自定义字符串为方法名称 methodinfo.Invoke(methom, null);//运行方法 } catch (Exception ex) { throw; } throw; } finally { Console.WriteLine("AddAsync方法结束"); } } }