码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET Core-使用AspNetCore实现AOP

时间:2020-01-31 23:10:19      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:dict   icp   nbsp   nuget   gate   injector   style   gets   cto   

引用 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 的姓名是张三";
        }
    }

 

未完待续...

ASP.NET Core-使用AspNetCore实现AOP

标签:dict   icp   nbsp   nuget   gate   injector   style   gets   cto   

原文地址:https://www.cnblogs.com/fanfan-90/p/12246735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!