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)
                });
            }

        }
    }
}

猜你喜欢

转载自www.cnblogs.com/rohmeng/p/11062012.html