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

 

未完待續...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM