context.Parameters); if (_cacheDict.ContainsKey(keyName)){c
引用 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
,温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30815.html