Intercept the call to an async method using DynamicProxy

后端 未结 8 1004
隐瞒了意图╮
隐瞒了意图╮ 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:00

    Trying to clarify with a generic and clean solution for:

    • Intercepting async methods adding custom code as a continuation task.

    I think the best solution is to use the dynamic keyword to bypass the compiler type checking and resolve the difference between Task and Task at run time:

    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
        var method = invocation.MethodInvocationTarget;
        var isAsync = method.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null;
        if (isAsync && typeof(Task).IsAssignableFrom(method.ReturnType))
        {
            invocation.ReturnValue = InterceptAsync((dynamic)invocation.ReturnValue);
        }
    }
    
    private static async Task InterceptAsync(Task task)
    {
        await task.ConfigureAwait(false);
        // do the logging here, as continuation work for Task...
    }
    
    private static async Task InterceptAsync(Task task)
    {
        T result = await task.ConfigureAwait(false);
        // do the logging here, as continuation work for Task...
        return result;
    }
    

提交回复
热议问题