/// <summary> /// 拦截同步执行的方法 /// </summary> /// <param name="invocation"></param> public void InterceptSynchronous(IInvocation invocation) { if (TryBegin(invocation)) { invocation.Proceed(); _logger.LogInformation($"事务{0}提交前!!!", invocation.GetHashCode()); _unitOfWork.Commit(); _logger.LogInformation($"事务{0}提交成功!!!", invocation.GetHashCode()); } else { invocation.Proceed(); } }
/// <summary> /// 有返回值的 异步/同步 方法拦截 /// </summary> /// <param name="invocation">IInvocation</param> /// <param name="proceed">Func<IInvocation, Task></param> protected override async Task <TResult> InterceptAsync <TResult>(IInvocation invocation, Func <IInvocation, Task <TResult> > proceed) { var methodInfo = invocation.MethodInvocationTarget ?? invocation.Method; var cachingAttribute = methodInfo.GetCustomAttributes(typeof(CachingAttribute), false).FirstOrDefault(); if (cachingAttribute is CachingAttribute attribute) { var methodName = $"开启缓存拦截:{methodInfo.Name}()->"; var hashCode = invocation.GetHashCode(); using (_logger.BeginScope("_cache_Result_Intercept:{hashCode}", hashCode)) { try { var cachingKey = CustomCacheKey(invocation); var cacheValue = await _caching.GetAsync(cachingKey); if (cacheValue != null) { return(cacheValue.FromJson <TResult>()); } var result = await proceed(invocation).ConfigureAwait(false); if (cachingKey.IsNotNullOrWhiteSpace()) { var timeSpan = attribute.ExpirationType switch { ExpirationType.Second => TimeSpan.FromSeconds(attribute.AbsoluteExpiration), ExpirationType.Hour => TimeSpan.FromHours(attribute.AbsoluteExpiration), ExpirationType.Day => TimeSpan.FromDays(attribute.AbsoluteExpiration), _ => TimeSpan.FromMinutes(attribute.AbsoluteExpiration), }; await _caching.SetAsync(cachingKey, result.ToJson(), timeSpan); } return(result); } catch (Exception ex) { _logger.LogError($"{methodName}开启缓存出现异常,异常原因:{ex.Message + ex.InnerException}."); throw new NpsException(ex.Message, StatusCode.Error); } } } else { return(await proceed(invocation).ConfigureAwait(false)); } }
/// <summary> /// 无返回值的 异步/同步 方法拦截 /// </summary> /// <param name="invocation">IInvocation</param> /// <param name="proceed">Func<IInvocation, Task></param> protected override async Task InterceptAsync(IInvocation invocation, Func <IInvocation, Task> proceed) { var methodName = $"执行{invocation.MethodInvocationTarget.DeclaringType?.FullName}.{invocation.Method.Name}()->"; var hashCode = invocation.GetHashCode(); using (_logger.BeginScope("_service_Intercept:{hashCode}", hashCode)) { try { MiniProfiler.Current.Step(methodName); await proceed(invocation).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError($"执行{methodName}出现异常,异常原因:{ex.Message + ex.InnerException}."); throw new NpsException(ex.Message, StatusCode.Error); } } }