示例#1
0
        public override void Intercept(IInvocation invocation)
        {
            MethodInfo methodInfo;

            try
            {
                methodInfo = invocation.MethodInvocationTarget;
            }
            catch
            {
                methodInfo = invocation.GetConcreteMethod();
            }

            if (!UnitOfWorkHelper.IsUnitOfWorkMethod(invocation.Method, out var unitOfWorkAttribute))
            {
                invocation.Proceed();
            }
            else
            {
                using (var unitOfWork = _unitOfWorkManager.Begin(CreateOptions(invocation, unitOfWorkAttribute)))
                {
                    invocation.Proceed();
                    if (!invocation.Method.IsAsync())
                    {
                        unitOfWork.Complete();
                    }
                    else
                    {
                        if (invocation.Method.ReturnType == typeof(Task))
                        {
                            invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
                                (Task)invocation.ReturnValue,
                                async() =>
                            {
                                await unitOfWork.CompleteAsync();
                                await Task.FromResult(0);
                            },
                                exception => unitOfWork.Dispose()
                                );
                        }
                        else //Task<TResult>
                        {
                            invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
                                invocation.Method.ReturnType.GenericTypeArguments[0],
                                invocation.ReturnValue,
                                async() =>
                            {
                                await unitOfWork.CompleteAsync();
                                await Task.FromResult(0);
                            },
                                exception => unitOfWork.Dispose()
                                );
                        }
                    }
                }
            }
        }
示例#2
0
        /// <summary>
        /// 实例化IInterceptor唯一方法
        /// </summary>
        /// <param name="invocation">包含被拦截方法的信息</param>
        public void Intercept(IInvocation invocation)
        {
            var method = invocation.MethodInvocationTarget ?? invocation.Method;

            //对当前方法的特性验证
            //如果需要验证
            if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(UseTranAttribute)) is UseTranAttribute)
            {
                try
                {
                    Console.WriteLine($"Begin Transaction");

                    _unitOfWork.BeginTran();

                    invocation.Proceed();


                    // 异步获取异常,先执行
                    if (IsAsyncMethod(invocation.Method))
                    {
                        if (invocation.Method.ReturnType == typeof(Task))
                        {
                            invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
                                (Task)invocation.ReturnValue,
                                async() => await TestActionAsync(invocation),
                                ex =>
                            {
                                _unitOfWork.RollbackTran();
                            });
                        }
                        else                         //Task<TResult>
                        {
                            invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
                                invocation.Method.ReturnType.GenericTypeArguments[0],
                                invocation.ReturnValue,
                                async() => await TestActionAsync(invocation),
                                ex =>
                            {
                                _unitOfWork.RollbackTran();
                            });
                        }
                    }
                    _unitOfWork.CommitTran();
                }
                catch (Exception)
                {
                    Console.WriteLine($"Rollback Transaction");
                    _unitOfWork.RollbackTran();
                }
            }
            else
            {
                invocation.Proceed();                //直接执行被拦截方法
            }
        }
 public void Intercept(IInvocation invocation)
 {
     if (ShouldIntercept(invocation))
     {
         Intercept(invocation, InternalAsyncHelper.IsAsyncMethod(invocation.Method));
     }
     else
     {
         invocation.Proceed();
     }
 }
示例#4
0
        public void Intercept(IInvocation invocation)
        {
            var method         = invocation.MethodInvocationTarget ?? invocation.Method;
            var transactionAtt = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(UnitOfWorkAttribute));

            if (transactionAtt is UnitOfWorkAttribute)
            {
                try
                {
                    Console.WriteLine($"Begin Transaction");

                    _unitOfWork.BeginTran();

                    invocation.Proceed();


                    // 异步获取异常,先执行
                    if (InternalAsyncHelper.IsAsyncMethod(invocation.Method))
                    {
                        if (invocation.Method.ReturnType == typeof(Task))
                        {
                            invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
                                (Task)invocation.ReturnValue,
                                ex =>
                            {
                                _unitOfWork.RollbackTran();
                            });
                        }
                        else //Task<TResult>
                        {
                            invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
                                invocation.Method.ReturnType.GenericTypeArguments[0],
                                invocation.ReturnValue,
                                ex =>
                            {
                                _unitOfWork.RollbackTran();
                            });
                        }
                    }
                    _unitOfWork.CommitTran();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    _unitOfWork.RollbackTran();
                }
            }
            else
            {
                //如果没有标记[UnitOfWork],直接执行方法
                invocation.Proceed();
            }
        }
示例#5
0
        public async Task Should_Call_Finally_On_Success()
        {
            var calledFinally = false;

            await InternalAsyncHelper.AwaitTaskWithFinally(
                MyMethod1Async(),
                exception =>
            {
                calledFinally = true;
                exception.ShouldBe(null);
            });

            calledFinally.ShouldBe(true);
        }
示例#6
0
 private void InterceptAsyncMethod(IInvocation invocation)
 {
     if (invocation.Method.ReturnType == typeof(Task))
     {
         invocation.ReturnValue = _abpInterceptor.InterceptAsync(new CastleAbpMethodInvocationAdapter(invocation));
     }
     else
     {
         var interceptResult   = _abpInterceptor.InterceptAsync(new CastleAbpMethodInvocationAdapter(invocation));
         var actualReturnValue = invocation.ReturnValue;
         invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPreActionAndPostActionAndFinallyAndGetResult(
             invocation.Method.ReturnType.GenericTypeArguments[0],
             () => actualReturnValue,
             () => interceptResult
             );
     }
 }
示例#7
0
        public async Task Should_Call_Finally_On_Exception()
        {
            var calledFinally = false;

            await Assert.ThrowsAsync <Exception>(async() =>
            {
                await InternalAsyncHelper.AwaitTaskWithFinally(
                    MyMethod1Async(true),
                    exception =>
                {
                    calledFinally = true;
                    exception.ShouldNotBe(null);
                    exception.Message.ShouldBe("test exception");
                });
            });

            calledFinally.ShouldBe(true);
        }
示例#8
0
        private void PerformAsyncAuditing(IInvocation invocation, AuditInfo auditInfo)
        {
            var stopwatch = Stopwatch.StartNew();

            invocation.Proceed();

            if (invocation.Method.ReturnType == typeof(Task))
            {
                invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithFinally((Task)invocation.ReturnValue, exception => SaveAuditInfo(auditInfo, stopwatch, exception));
            }
            else //Task<TResult>
            {
                invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithFinallyAndGetResult(
                    invocation.Method.ReturnType.GenericTypeArguments[0],
                    invocation.ReturnValue,
                    exception => SaveAuditInfo(auditInfo, stopwatch, exception)
                    );
            }
        }
示例#9
0
        private void PerformAsyncUow(IInvocation invocation, UnitOfWorkOptions options)
        {
            var uow = _unitOfWorkManager.Begin(options);

            try
            {
                invocation.Proceed();
            }
            catch
            {
                uow.Dispose();
                throw;
            }

            if (invocation.Method.ReturnType == typeof(Task))
            {
                invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
                    (Task)invocation.ReturnValue,
                    async() =>
                {
                    uow.Complete();
                    await Task.FromResult(0);
                },
                    exception => uow.Dispose()
                    );
            }
            else //Task<TResult>
            {
                invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
                    invocation.Method.ReturnType.GenericTypeArguments[0],
                    invocation.ReturnValue,
                    async() =>
                {
                    uow.Complete();
                    await Task.FromResult(0);
                },
                    exception => uow.Dispose()
                    );
            }
        }
        private void ProceedAndCallPostTreatment <T>(IInvocation invocation, List <T> pEntities, bool IsAsync)
        {
            invocation.Proceed();


            if (IsAsync)
            {
                ////Wait task execution and modify return value
                if (invocation.Method.ReturnType == typeof(Task))
                {
                    invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
                        (Task)invocation.ReturnValue,
                        async() =>
                    {
                        GenericPostTreatment(invocation, pEntities);
                    },
                        ex =>
                    {
                    });
                }
                else //Task<TResult>
                {
                    invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
                        invocation.Method.ReturnType.GenericTypeArguments[0],
                        invocation.ReturnValue,
                        async(e) =>
                    {
                        invocation.ReturnValue = e;
                        GenericPostTreatment(invocation, pEntities);
                    },
                        ex =>
                    {
                    });
                }
            }
            else
            {
                this.GenericPostTreatment(invocation, pEntities);
            }
        }
        private void InterceptAsync(IInvocation invocation, IEnumerable <AbpAuthorizeAttribute> authorizeAttributes)
        {
            var authorizationAttributeHelper = _iocResolver.ResolveAsDisposable <IAuthorizeAttributeHelper>();

            if (invocation.Method.ReturnType == typeof(Task))
            {
                invocation.ReturnValue = InternalAsyncHelper.InvokeWithPreAndFinalActionAsync(
                    invocation,
                    async() => await authorizationAttributeHelper.Object.AuthorizeAsync(authorizeAttributes),
                    () => _iocResolver.Release(authorizationAttributeHelper)
                    );
            }
            else
            {
                invocation.ReturnValue = InternalAsyncHelper.CallInvokeWithPreAndFinalActionAsync(
                    invocation.Method.ReturnType.GenericTypeArguments[0],
                    invocation,
                    async() => await authorizationAttributeHelper.Object.AuthorizeAsync(authorizeAttributes),
                    () => _iocResolver.Release(authorizationAttributeHelper)
                    );
            }
        }
示例#12
0
        private void PerformAsync(IInvocation invocation)
        {
            PerformSync(invocation);

            if (invocation.Method.ReturnType == typeof(Task))
            {
                invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithFinally(
                    (Task)invocation.ReturnValue,
                    ex =>
                {
                    ExceptionHanding(ex);
                });
            }
            else //Task<TResult>
            {
                invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithFinallyAndGetResult(
                    invocation.Method.ReturnType.GenericTypeArguments[0],
                    invocation.ReturnValue,
                    ex =>
                {
                    ExceptionHanding(ex);
                });
            }
        }
示例#13
0
        private void PerformAsyncUow(IInvocation invocation, UnitOfWorkOptions options)
        {
            var uow = _unitOfWorkManager.Begin(options);

            invocation.Proceed();

            if (invocation.Method.ReturnType == typeof(Task))
            {
                invocation.ReturnValue = InternalAsyncHelper.WaitTaskAndActionWithFinally(
                    (Task)invocation.ReturnValue,
                    async() => await uow.CompleteAsync(),
                    uow.Dispose
                    );
            }
            else //Task<TResult>
            {
                invocation.ReturnValue = InternalAsyncHelper.CallReturnGenericTaskAfterAction(
                    invocation.Method.ReturnType.GenericTypeArguments[0],
                    invocation.ReturnValue,
                    async() => await uow.CompleteAsync(),
                    uow.Dispose
                    );
            }
        }
        private void ValidateBeforeProceeding(IInvocation invocation)
        {
            //le invocation vas être destiné (target) a un IBaseValidatedAppService, car dans le ValidationRegistrar dans la méthode Kernel_ComponentRegistered
            //seulement les IBaseRestApplicationService sont handle par l'Interceptor.
            IBaseValidatedAppService appService = invocation.InvocationTarget as IBaseValidatedAppService;

            string assemblyName = invocation.InvocationTarget.GetType().BaseType.Assembly.ManifestModule.Name.Replace(".dll", ".");

            string validatorName = "I" + appService.GetType().BaseType.Name + "Validator";

            TypeResolver typeResolver = _iocResolver.Resolve <TypeResolver>();

            Type validatorInterfaceType = typeResolver[assemblyName + validatorName];

            if (validatorInterfaceType is null)
            {
                return;
            }

            IBaseValidator baseValidator = _iocResolver.Resolve(validatorInterfaceType) as IBaseValidator;

            Type validatorType = baseValidator.GetType();

            //IocManager.Instance.IocContainer.Resolve("");
            //on vas essayer d'aller chercher par réflection les méthode de validation
            //on vas devoir avoir un standard que les méthode dans les Validator qui hérite de IBaseValidation
            //doivent avoir le même nom que la méthode du app service qu'elle valide plus le terme Validation
            string methodName = invocation.MethodInvocationTarget.Name + "Validation";

            MethodInfo method = validatorType.GetMethod(methodName);

            if (method != null)
            {
                //on invoke la méthode du validator
                //on doit faire le try catch et le re-throw ici sinon on perdait le type de l'exception
                try
                {
                    if (InternalAsyncHelper.IsAsyncMethod(method))
                    {
                        var returnValue = method.Invoke(baseValidator, invocation.Arguments);
                        ////Wait task execution and modify return value
                        if (method.ReturnType == typeof(Task))
                        {
                            returnValue = InternalAsyncHelper.AwaitTaskWithFinally(
                                (Task)returnValue,
                                ex =>
                            {
                                invocation.Proceed();
                            });
                        }
                        else //Task<TResult>
                        {
                            returnValue = InternalAsyncHelper.CallAwaitTaskWithFinallyAndGetResult(
                                method.ReturnType.GenericTypeArguments[0],
                                returnValue,
                                ex =>
                            {
                                invocation.Proceed();
                            });
                        }
                    }
                    else
                    {
                        invocation.Proceed();
                    }
                }
                catch (Exception ex)
                {
                    throw ex.InnerException;
                }
            }
            else
            {
            }
        }
示例#15
0
        public void Intercept(IInvocation invocation)
        {
            // 记录被拦截方法信息的日志信息
            var interceptorInfo = "" +
                                  $"【当前执行方法】:{ invocation.Method.Name} \r\n" +
                                  $"【携带的参数有】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n";

            try
            {
                // 在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的
                invocation.Proceed();

                // 异步获取异常,先执行
                if (IsAsyncMethod(invocation.Method))
                {
                    #region 方案一
                    // Wait task execution and modify return value
                    if (invocation.Method.ReturnType == typeof(Task))
                    {
                        invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
                            (Task)invocation.ReturnValue,
                            async() => await SuccessAction(invocation, interceptorInfo), /*成功时执行*/
                            ex =>
                        {
                            System.Console.WriteLine(ex.Message);
                        });
                    }
                    // Task<TResult>
                    else
                    {
                        invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
                            invocation.Method.ReturnType.GenericTypeArguments[0],
                            invocation.ReturnValue,
                            async(o) => await SuccessAction(invocation, interceptorInfo, o),/*成功时执行*/
                            ex =>
                        {
                            System.Console.WriteLine(ex);
                        });
                    }
                    #endregion

                    // 如果方案一不行,试试这个方案
                    #region 方案二
                    //var type = invocation.Method.ReturnType;
                    //var resultProperty = type.GetProperty("Result");
                    //dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue))}");

                    //Parallel.For(0, 1, e =>
                    //{
                    //    LogLock.OutSql2Log("AOPLog", new string[] { dataIntercept });
                    //});
                    #endregion
                }
                else
                {
                    // 同步1
                    interceptorInfo += ($"【执行完成结果】:{invocation.ReturnValue}");
                    Parallel.For(0, 1, e =>
                    {
                        System.Console.WriteLine(interceptorInfo);
                    });
                }
            }
            catch (Exception ex)// 同步2
            {
                System.Console.WriteLine(ex.Message + interceptorInfo);
            }
        }
示例#16
0
        private void PreTreatmentBeforeProceeding(IInvocation invocation)
        {
            IPreTreatmentAppService appService = invocation.InvocationTarget as IPreTreatmentAppService;

            string assemblyName = invocation.InvocationTarget.GetType().BaseType.Assembly.ManifestModule.Name.Replace(".dll", ".");

            string preTreatmentExecutorName = "I" + appService.GetType().BaseType.Name + "PreTreatmentExecutor";

            TypeResolver typeResolver = _iocResolver.Resolve <TypeResolver>();

            Type preTreatmentExecutorInterfaceType = typeResolver[assemblyName + preTreatmentExecutorName];

            if (preTreatmentExecutorInterfaceType is null)
            {
                return;
            }

            IPreTreatmentExecutor preTreatmentExecutor = _iocResolver.Resolve(preTreatmentExecutorInterfaceType) as IPreTreatmentExecutor;

            Type preTreatmentExecutorType = preTreatmentExecutor.GetType();

            string methodName = "PreTreatment_" + invocation.MethodInvocationTarget.Name;

            MethodInfo method = preTreatmentExecutorType.GetMethod(methodName);

            var request = invocation.Arguments[0];


            if (method != null)
            {
                try
                {
                    var returnValue = method.Invoke(preTreatmentExecutor, invocation.Arguments);

                    if (InternalAsyncHelper.IsAsyncMethod(method))
                    {
                        //Wait task execution and modify return value
                        if (method.ReturnType == typeof(Task))
                        {
                            invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithFinally(
                                (Task)returnValue,
                                ex =>
                            {
                                invocation.Proceed();
                            });
                        }
                        else //Task<TResult>
                        {
                            invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithFinallyAndGetResult(
                                method.ReturnType.GenericTypeArguments[0],
                                returnValue,
                                ex =>
                            {
                                invocation.Proceed();
                            });
                        }
                    }
                    else
                    {
                        invocation.Proceed();
                    }
                }
                catch (Exception ex)
                {
                    throw ex.InnerException;
                }
            }
        }