ASP.NET Core-使用AspNetCore实现AOP

2021-04-22 01:29

阅读:373

标签: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();
            var provider = services.BuildAspectInjectorProvider();
            var mysql = provider.GetService();
            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 Dictionarystring, object> _cacheDict = new Dictionarystring, 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


评论


亲,登录后才可以留言!