Пример #1
0
        protected override async Task <TResult> InternalInterceptAsynchronous <TResult>(IInvocation invocation)
        {
            var proceedInfo    = invocation.CaptureProceedInfo();
            var method         = GetMethodInfo(invocation);
            var unitOfWorkAttr = _unitOfWorkOptions.GetUnitOfWorkAttributeOrNull(method);

            if (unitOfWorkAttr == null || unitOfWorkAttr.IsDisabled)
            {
                proceedInfo.Invoke();
                var taskResult = (Task <TResult>)invocation.ReturnValue;
                return(await taskResult.ConfigureAwait(false));
            }

            using (var uow = _unitOfWorkManager.Begin(unitOfWorkAttr.CreateOptions()))
            {
                proceedInfo.Invoke();

                var taskResult = (Task <TResult>)invocation.ReturnValue;
                var result     = await taskResult.ConfigureAwait(false);

                await uow.CompleteAsync().ConfigureAwait(false);

                return(result);
            }
        }
Пример #2
0
        public InterceptedInput(IFunction function, InterceptedMethodDescriptor method, IInvocation invocation)
            : base(function)
        {
            Method      = method;
            Invocation  = invocation;
            ProceedInfo = invocation.CaptureProceedInfo();

            var arguments        = invocation.Arguments;
            var argumentHandlers = method.ArgumentHandlers;
            var preprocessingArgumentHandlers = method.PreprocessingArgumentHandlers;

            if (preprocessingArgumentHandlers != null)
            {
                foreach (var(handler, index) in preprocessingArgumentHandlers)
                {
                    handler.PreprocessFunc !.Invoke(method, invocation, index);
                }
            }

            var hashCode = System.HashCode.Combine(
                HashCode,
                method.InvocationTargetHandler.GetHashCodeFunc(invocation.InvocationTarget));

            for (var i = 0; i < arguments.Length; i++)
            {
                hashCode ^= argumentHandlers[i].GetHashCodeFunc(arguments[i]);
            }
            HashCode = hashCode;
        }
        private async Task InterceptAsync(IInvocation invocation)
        {
            var proceed = invocation.CaptureProceedInfo();
            await Task.CompletedTask;

            proceed.Invoke(); // will not proceed, but reenter this interceptor
                              // or--if this isn't the first--an earlier one!
        }
        protected override async Task InternalInterceptAsynchronous(IInvocation invocation)
        {
            var proceedInfo = invocation.CaptureProceedInfo();

            await _authorizationHelper.AuthorizeAsync(invocation.MethodInvocationTarget, invocation.TargetType);

            proceedInfo.Invoke();
            var task = (Task)invocation.ReturnValue;
            await task.ConfigureAwait(false);
        }
        public void InterceptAsynchronous <TResult>(IInvocation invocation)
        {
            var capture = invocation.CaptureProceedInfo();

            invocation.ReturnValue = _asyncPolicy
                                     .ExecuteAsync(() =>
            {
                capture.Invoke();
                return((Task <TResult>)invocation.ReturnValue);
            });
        }
        protected override async Task <TResult> InternalInterceptAsynchronous <TResult>(IInvocation invocation)
        {
            var proceedInfo = invocation.CaptureProceedInfo();

            await _authorizationHelper.AuthorizeAsync(invocation.MethodInvocationTarget, invocation.TargetType);

            proceedInfo.Invoke();
            var taskResult = (Task <TResult>)invocation.ReturnValue;

            return(await taskResult);
        }
Пример #7
0
 protected override async Task InterceptAsync(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func <IInvocation, IInvocationProceedInfo, Task> proceed)
 {
     try
     {
         // Cannot simply return the the task, as any exceptions would not be caught below.
         await proceed(invocation, invocation.CaptureProceedInfo()).ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         _logger.LogError($"Error calling {invocation.Method.Name}.", ex);
         throw;
     }
 }
        public void InterceptSynchronous(IInvocation invocation)
        {
            var capture = invocation.CaptureProceedInfo();

            invocation.ReturnValue = _asyncPolicy
                                     .ExecuteAsync(() =>
            {
                capture.Invoke();
                return(Task.FromResult(invocation.ReturnValue));
            })
                                     .ConfigureAwait(false)
                                     .GetAwaiter()
                                     .GetResult();
        }
        private async ValueTask InterceptAsync(IInvocation invocation)
        {
            var proceed = invocation.CaptureProceedInfo();
            FixtureEventHandler target       = (invocation.InvocationTarget as FixtureEventHandler) !;
            FixtureEvent        fixtureEvent = (invocation.Arguments[0] as FixtureEvent) !;
            await target.HandleAsync(fixtureEvent);

            await target.Repository.FixtureEventsInDatabase.AddAsync(
                FixtureEventInDatabase.GetEntity(fixtureEvent));

            await target.Repository.SaveChangesAsync();

            proceed.Invoke();
        }
            private static async Task InterceptAsyncMethod(IInvocation invocation)
            {
                var proceed = invocation.CaptureProceedInfo();

                await Task.Delay(10).ConfigureAwait(false);

                proceed.Invoke();

                // Return value is being set in two situations, but this doesn't matter
                // for the above test.
                Task returnValue = (Task)invocation.ReturnValue;

                await returnValue.ConfigureAwait(false);
            }
        protected override async Task <TResult> InternalInterceptAsynchronous <TResult>(IInvocation invocation)
        {
            var proceedInfo = invocation.CaptureProceedInfo();

            if (AbpCrossCuttingConcerns.IsApplied(invocation.InvocationTarget, AbpCrossCuttingConcerns.Auditing))
            {
                proceedInfo.Invoke();
                var taskResult = (Task <TResult>)invocation.ReturnValue;
                return(await taskResult.ConfigureAwait(false));
            }

            if (!_auditingHelper.ShouldSaveAudit(invocation.MethodInvocationTarget))
            {
                proceedInfo.Invoke();
                var taskResult = (Task <TResult>)invocation.ReturnValue;
                return(await taskResult.ConfigureAwait(false));
            }

            var auditInfo = _auditingHelper.CreateAuditInfo(invocation.TargetType, invocation.MethodInvocationTarget, invocation.Arguments);

            var     stopwatch = Stopwatch.StartNew();
            TResult result;

            try
            {
                proceedInfo.Invoke();
                var taskResult = (Task <TResult>)invocation.ReturnValue;
                result = await taskResult.ConfigureAwait(false);

                if (_auditingConfiguration.SaveReturnValues && result != null)
                {
                    auditInfo.ReturnValue = _auditSerializer.Serialize(result);
                }
            }
            catch (Exception ex)
            {
                auditInfo.Exception = ex;
                throw;
            }
            finally
            {
                stopwatch.Stop();
                auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);

                await _auditingHelper.SaveAsync(auditInfo).ConfigureAwait(false);
            }

            return(result);
        }
Пример #12
0
        public void Intercept(IInvocation invocation)
        {
            var proceedInfo = invocation.CaptureProceedInfo();

            var method = invocation.MethodInvocationTarget ?? invocation.Method;

            if (method.IsAsync())
            {
                InterceptAsyncMethod(invocation, proceedInfo);
            }
            else
            {
                InterceptSyncMethod(invocation, proceedInfo);
            }
        }
        /// <summary>
        /// Intercepts an asynchronous method <paramref name="invocation"/> with return type of <see cref="Task{T}"/>.
        /// </summary>
        /// <typeparam name="TResult">The type of the <see cref="Task{T}"/> <see cref="Task{T}.Result"/>.</typeparam>
        /// <param name="invocation">The method invocation.</param>
        void IAsyncInterceptor.InterceptAsynchronous <TResult>(IInvocation invocation)
        {
            Task task = Task.Run(() => InterceptAsync(invocation, invocation.CaptureProceedInfo(), ProceedAsynchronous <TResult>));

            // prevent exception propagation
            try
            {
                task.GetAwaiter().GetResult();
            }
            catch (Exception)
            {
            }

            invocation.ReturnValue = task;
        }
        private static void InterceptSynchronousResult <TResult>(AsyncInterceptorBase me, IInvocation invocation)
        {
            Task <TResult> task = me.InterceptAsync(invocation, invocation.CaptureProceedInfo(), ProceedSynchronous <TResult>);

            // If the intercept task has yet to complete, wait for it.
            if (!task.IsCompleted)
            {
                // Need to use Task.Run() to prevent deadlock in .NET Framework ASP.NET requests.
                // GetAwaiter().GetResult() prevents a thrown exception being wrapped in a AggregateException.
                // See https://stackoverflow.com/a/17284612
                Task.Run(() => task).GetAwaiter().GetResult();
            }

            task.RethrowIfFaulted();
        }
Пример #15
0
        protected override async Task <TResult> InterceptAsync <TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func <IInvocation, IInvocationProceedInfo, Task <TResult> > proceed)
        {
            try
            {
                _logger.LogInformation($"Calling method {invocation.TargetType}.{invocation.Method.Name} input {invocation.Arguments.ToJson()}.");
                var result = await proceed(invocation, invocation.CaptureProceedInfo()).ConfigureAwait(false);

                _logger.LogInformation($"Salida method {invocation.TargetType}.{invocation.Method.Name} salida {result.ToJson()}.");
                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogError($"*********************************Error calling {invocation.Method.Name}. {ex.ToString()}", ex);
                throw;
            }
        }
Пример #16
0
        public void InterceptAsynchronous <TResult>(IInvocation invocation)
        {
            if (!_policyRegistry.TryGetAsyncPolicy(invocation, out var asyncPolicy))
            {
                invocation.Proceed();
                return;
            }

            var capture = invocation.CaptureProceedInfo();

            invocation.ReturnValue = asyncPolicy
                                     .ExecuteAsync(ctx =>
            {
                capture.Invoke();
                return((Task <TResult>)invocation.ReturnValue);
            },
                                                   new Context(CreateOperationKey(invocation)));
        }
        protected override async Task InternalInterceptAsynchronous(IInvocation invocation)
        {
            var proceedInfo = invocation.CaptureProceedInfo();

            if (AbpCrossCuttingConcerns.IsApplied(invocation.InvocationTarget, AbpCrossCuttingConcerns.Auditing))
            {
                proceedInfo.Invoke();
                var   task = (Task)invocation.ReturnValue;
                await task;
                return;
            }

            if (!_auditingHelper.ShouldSaveAudit(invocation.MethodInvocationTarget))
            {
                proceedInfo.Invoke();
                var   task = (Task)invocation.ReturnValue;
                await task;
                return;
            }

            var auditInfo = _auditingHelper.CreateAuditInfo(invocation.TargetType, invocation.MethodInvocationTarget, invocation.Arguments);

            var stopwatch = Stopwatch.StartNew();

            try
            {
                proceedInfo.Invoke();
                var   task = (Task)invocation.ReturnValue;
                await task;
            }
            catch (Exception ex)
            {
                auditInfo.Exception = ex;
                throw;
            }
            finally
            {
                stopwatch.Stop();
                auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);

                await _auditingHelper.SaveAsync(auditInfo);
            }
        }
        protected override async Task <TResult> InternalInterceptAsynchronous <TResult>(IInvocation invocation)
        {
            var proceedInfo = invocation.CaptureProceedInfo();

            if (AbpCrossCuttingConcerns.IsApplied(invocation.InvocationTarget, AbpCrossCuttingConcerns.Validation))
            {
                proceedInfo.Invoke();
                return(await((Task <TResult>)invocation.ReturnValue));
            }

            using (var validator = _iocResolver.ResolveAsDisposable <MethodInvocationValidator>())
            {
                validator.Object.Initialize(invocation.MethodInvocationTarget, invocation.Arguments);
                validator.Object.Validate();
            }

            proceedInfo.Invoke();
            return(await((Task <TResult>)invocation.ReturnValue));
        }
Пример #19
0
        public void InterceptAsynchronous <TResult>(IInvocation invocation)
        {
            if (!TryGetCacheEntryOptions(invocation, out var options))
            {
                invocation.Proceed();
                return;
            }

            var capture = invocation.CaptureProceedInfo();

            var cancellationArg = invocation.Arguments.FirstOrDefault(a => a is CancellationToken);

            invocation.ReturnValue = _cache.GetOrCreateAsync(CreateOperationKey(invocation),
                                                             options,
                                                             _ =>
            {
                capture.Invoke();
                return((Task <TResult>)invocation.ReturnValue);
            },
                                                             (CancellationToken?)cancellationArg ?? default);
        }
Пример #20
0
        public void Intercept(IInvocation invocation)
        {
            MethodType methodType = invocation.Method.GetMethodType();

            var proceedInfo = invocation.CaptureProceedInfo();

            switch (methodType)
            {
            case MethodType.AsyncAction:
                invocation.ReturnValue = HandleAsyncMethodInfo.Invoke(this, new object[] { invocation, proceedInfo });
                return;

            case MethodType.AsyncFunction:
                invocation.ReturnValue = GetHandlerMethod(invocation.Method.ReturnType).Invoke(this, new object[] { invocation, proceedInfo });
                return;

            default:
                _miCakeInterceptor.Intercept(new CastleMiCakeInvocationAdaptor(invocation, proceedInfo));
                return;
            }
        }
        protected override async Task InternalInterceptAsynchronous(IInvocation invocation)
        {
            var proceedInfo    = invocation.CaptureProceedInfo();
            var method         = GetMethodInfo(invocation);
            var unitOfWorkAttr = _unitOfWorkOptions.GetUnitOfWorkAttributeOrNull(method);

            if (unitOfWorkAttr == null || unitOfWorkAttr.IsDisabled)
            {
                proceedInfo.Invoke();
                var   task = (Task)invocation.ReturnValue;
                await task;
                return;
            }

            using (var uow = _unitOfWorkManager.Begin(unitOfWorkAttr.CreateOptions()))
            {
                proceedInfo.Invoke();
                var   task = (Task)invocation.ReturnValue;
                await task;
                await uow.CompleteAsync();
            }
        }
Пример #22
0
        protected override async Task <TResult> InternalInterceptAsynchronous <TResult>(IInvocation invocation)
        {
            var proceedInfo = invocation.CaptureProceedInfo();

            var methodInfo       = invocation.MethodInvocationTarget;
            var useCaseAttribute = methodInfo.GetCustomAttributes(true).OfType <UseCaseAttribute>().FirstOrDefault()
                                   ?? methodInfo.DeclaringType.GetCustomAttributes(true).OfType <UseCaseAttribute>().FirstOrDefault();

            if (useCaseAttribute?.Description == null)
            {
                proceedInfo.Invoke();
                var taskResult = (Task <TResult>)invocation.ReturnValue;
                return(await taskResult.ConfigureAwait(false));
            }

            using (ReasonProvider.Use(useCaseAttribute.Description))
            {
                proceedInfo.Invoke();
                var taskResult = (Task <TResult>)invocation.ReturnValue;
                return(await taskResult.ConfigureAwait(false));
            }
        }
        private static void InterceptSynchronousResult <TResult>(AsyncInterceptorBase me, IInvocation invocation)
        {
            try
            {
                Task <TResult> task = Task.Run(() => me.InterceptAsync(invocation, invocation.CaptureProceedInfo(), ProceedSynchronous <TResult>));
                invocation.ReturnValue = task.GetAwaiter().GetResult();

                //TODO: check
                // Task<TResult> task = me.InterceptAsync(invocation, invocation.CaptureProceedInfo(), ProceedSynchronous<TResult>);
                // if (!task.IsCompleted)
                // {
                //     // Need to use Task.Run() to prevent deadlock in .NET Framework ASP.NET requests.
                //     // GetAwaiter().GetResult() prevents a thrown exception being wrapped in a AggregateException.
                //     // See https://stackoverflow.com/a/17284612
                //     Task.Run(() => task).GetAwaiter().GetResult();
                // }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="invocation"></param>
        /// <exception cref="NotImplementedException"></exception>
        protected override void Intercept(IInvocation invocation)
        {
            #region 先从缓存里面拿到这个方法时候打了继承AspectInvokeAttribute的标签

            if (!_cache.CacheList.TryGetValue(invocation.MethodInvocationTarget, out var attribute))
            {
                //动态泛型类
                if (!invocation.MethodInvocationTarget.DeclaringType.GetTypeInfo().IsGenericType ||
                    (!_cache.DynamicCacheList.TryGetValue(invocation.MethodInvocationTarget.GetMethodInfoUniqueName(), out var AttributesDynamic)))
                {
                    invocation.Proceed();
                    return;
                }

                attribute = AttributesDynamic;
            }

            #endregion

            var catpture      = invocation.CaptureProceedInfo();
            var aspectContext = new AspectContext(_component, invocation);
            aspectContext.Proceed = () => {
                catpture.Invoke();
                return(new ValueTask());
            };

            var runTask = attribute.AspectFunc.Value;
            var task    = runTask(aspectContext);
            // If the intercept task has yet to complete, wait for it.
            if (!task.IsCompleted)
            {
                // Need to use Task.Run() to prevent deadlock in .NET Framework ASP.NET requests.
                // GetAwaiter().GetResult() prevents a thrown exception being wrapped in a AggregateException.
                // See https://stackoverflow.com/a/17284612
                Task.Run(() => task).GetAwaiter().GetResult();
            }
            task.RethrowIfFaulted();
        }
 public AsyncInvocation(IInvocation invocation)
 {
     this.invocation = invocation;
     this.proceed    = invocation.CaptureProceedInfo();
 }
 /// <summary>
 /// Intercepts an asynchronous method <paramref name="invocation"/> with return type of <see cref="Task{T}"/>.
 /// </summary>
 /// <typeparam name="TResult">The type of the <see cref="Task{T}"/> <see cref="Task{T}.Result"/>.</typeparam>
 /// <param name="invocation">The method invocation.</param>
 public void InterceptAsynchronous <TResult>(IInvocation invocation)
 {
     invocation.ReturnValue =
         InterceptAsync(invocation, invocation.CaptureProceedInfo(), ProceedAsynchronous <TResult>);
 }
 /// <summary>
 /// Intercepts an asynchronous method <paramref name="invocation"/> with return type of <see cref="Task"/>.
 /// </summary>
 /// <param name="invocation">The method invocation.</param>
 void IAsyncInterceptor.InterceptAsynchronous(IInvocation invocation)
 {
     invocation.ReturnValue = InterceptAsync(invocation, invocation.CaptureProceedInfo(), ProceedAsynchronous);
 }
Пример #28
0
 public InvocationAsyncBase(IInvocation invocation)
 {
     _proceed    = invocation.CaptureProceedInfo();
     _invocation = invocation;
 }
Пример #29
0
 internal Call(IInvocation invocation, IDecorator[] decorators)
 {
     _invocation  = invocation;
     _decorators  = decorators;
     _proceedInfo = invocation.CaptureProceedInfo();
 }