Intercept the call to an async method using DynamicProxy

后端 未结 8 1022
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 02:30

Below is the code from the Intercept method on a custom type that implements IInterceptor of the Castle Dynamic Proxy library. This snippet is from

8条回答
  •  一个人的身影
    2020-12-13 03:03

    Thanks to Jon's answer, this is what I ended up with:

    public void Intercept(IInvocation invocation)
    {
        if (Log.IsDebugEnabled) Log.Debug(CreateInvocationLogString("Called", invocation));
        try
        {
            invocation.Proceed();
    
            if (Log.IsDebugEnabled)
            {
                var returnType = invocation.Method.ReturnType;
                if (returnType != typeof(void))
                {
                    var returnValue = invocation.ReturnValue;
                    if (returnType == typeof(Task))
                    {
                        Log.Debug("Returning with a task.");
                    }
                    else if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
                    {
                        Log.Debug("Returning with a generic task.");
                        var task = (Task)returnValue;
                        task.ContinueWith((antecedent) =>
                                              {
                                                  var taskDescriptor = CreateInvocationLogString("Task from", invocation);
                                                  var result =
                                                      antecedent.GetType()
                                                                .GetProperty("Result")
                                                                .GetValue(antecedent, null);
                                                  Log.Debug(taskDescriptor + " returning with: " + result);
                                              });
                    }
                    else
                    {
                        Log.Debug("Returning with: " + returnValue);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            if (Log.IsErrorEnabled) Log.Error(CreateInvocationLogString("ERROR", invocation), ex);
            throw;
        }
    }
    

提交回复
热议问题