介绍:

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方法结束");
            }
        }
    }
View Code

相关文章:

  • 2021-11-23
  • 2022-12-23
  • 2021-08-09
  • 2022-12-23
  • 2021-04-21
  • 2019-09-02
  • 2022-12-23
猜你喜欢
  • 2021-06-29
  • 2021-12-02
  • 2021-09-28
  • 2021-09-14
  • 2022-12-23
  • 2021-11-28
相关资源
相似解决方案