• ASP.NET Core-使用AspNetCore实现AOP


    引用 AspectCore.Extensions.DependencyInjection 

    class Program
        {
            //Nuget:  AspectCore.Extensions.DependencyInjection
            static void Main(string[] args)
            {
                ServiceCollection services = new ServiceCollection();
                services.AddDynamicProxy();
                services.AddTransient<IMySql, MySql>();
                var provider = services.BuildAspectInjectorProvider();
                var mysql = provider.GetService<IMySql>();
                Console.WriteLine(mysql.GetData(5));
                Console.WriteLine(mysql.GetData(5));
                Console.WriteLine(mysql.GetData(5));
                Console.ReadKey();
            }
        }
        //记录日志AOP
        public class MyLogInterceptorAttribute : AbstractInterceptorAttribute
        {
            public override Task Invoke(AspectContext context, AspectDelegate next)
            {
                Console.WriteLine("方法之前记录日志-----");
                Task t = next(context);
                Console.WriteLine("方法之后记录日志-----");
                return t;
            }
        }
        //缓存AOP
        public class CacheInterceptorAttribute : AbstractInterceptorAttribute
        {
            private Dictionary<string, object> _cacheDict = new Dictionary<string, object>();
            public override Task Invoke(AspectContext context, AspectDelegate next)
            {
                string name = context.Proxy.ToString();
                string keyName = context.ProxyMethod.Name +"_"+ string.Join("_", context.Parameters);
                if (_cacheDict.ContainsKey(keyName))
                {
                    context.ReturnValue = _cacheDict[keyName];
                    return Task.CompletedTask;
                }
                Task t = next(context);
                _cacheDict[keyName] = "cache:"+context.ReturnValue;
                return t;
            }
        }
    
        public interface IMySql
        {
            string GetData(int id);
        }
        public class MySql : IMySql
        {
            //[MyLogInterceptor]
            [CacheInterceptor]
            public string GetData(int id)
            {
                Console.WriteLine("执行方法");
                return "mysql 返回 id=1 的姓名是张三";
            }
        }

    未完待续...

  • 相关阅读:
    DPM(Deformable Part Model)原理详解(汇总)
    VS code配置docker的shell环境
    C++运算符重载规则
    typedef 和define的区别
    在ESP分区新建win10引导
    自动化学报投稿过程记录
    shell-grep命令详解(转)
    shell-sed命令详解(转)
    shell-命令行参数(转)
    sublimetext3-实用快捷键整理
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12246735.html
Copyright © 2020-2023  润新知