码迷,mamicode.com
首页 > Web开发 > 详细

AspectCore的AOP操作

时间:2019-06-20 23:52:49      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:info   syn   only   microsoft   ado   res   mem   mic   wait   

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操作

标签:info   syn   only   microsoft   ado   res   mem   mic   wait   

原文地址:https://www.cnblogs.com/rohmeng/p/11062012.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!