AspectCore的AOP操作
Posted rohmeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AspectCore的AOP操作相关的知识,希望对你有一定的参考价值。
AOP实现缓存的一个例子
using AspectCore.DynamicProxy;
using Microsoft.Extensions.Caching.Memory;
[AttributeUsage(AttributeTargets.Method)]
public class MemoryCacheAttribute : AbstractInterceptorAttribute
public int Expiration get; set; = 2;
public string CacheKey get; set; = null;
private static readonly MethodInfo _taskResultMethod;
private readonly IMemoryCache _cache = MemoryCacheManager.GetInstance();
static MemoryCacheAttribute()
_taskResultMethod = typeof(Task).GetMethods().FirstOrDefault(p => p.Name == "FromResult" && p.ContainsGenericParameters);
public override async Task Invoke(AspectContext context, AspectDelegate next)
var parameters = context.ServiceMethod.GetParameters();
if (parameters.Any(it => it.IsIn || it.IsOut))
await next(context);
else
var key = string.IsNullOrEmpty(CacheKey)
? new CacheKey(context.ServiceMethod, parameters, context.Parameters).GetMemoryCacheKey()
: CacheKey;
var returnType = context.IsAsync()
? context.ServiceMethod.ReturnType.GetGenericArguments().First()
: context.ServiceMethod.ReturnType;
if (_cache.TryGetValue(key, out object value))
context.ReturnValue = context.IsAsync()
? _taskResultMethod.MakeGenericMethod(returnType).Invoke(null, new object[] value )
: value;
return;
else
await context.Invoke(next);
object returnValue = context.ReturnValue;
if (context.ServiceMethod.IsReturnTask())
returnValue = returnValue.GetPropertyValue("Result");
_cache.Set(key, returnValue, new MemoryCacheEntryOptions()
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(Expiration)
);
以上是关于AspectCore的AOP操作的主要内容,如果未能解决你的问题,请参考以下文章
.NET静态代码织入——肉夹馍(Rougamo) 发布1.1.0