zoukankan      html  css  js  c++  java
  • 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 的姓名是张三";
            }
        }

    未完待续...

  • 相关阅读:
    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
    Java中时间与时间戳的转换
    python爬取网页数据
    selenium爬取网页内容知识点总结(代码均亲测可用)
    【LeetCode 5】 最长回文子串
    【LeetCode 4】寻找两个有序数组的中位数
    【LeetCode 3】无重复字符的最长子串
    【LeetCode 1】两数之和
    【LeetCode 2】两数相加
    【3-4】数字三角形问题
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12246735.html
Copyright © 2011-2022 走看看