Intercept async method that returns generic Task<> via DynamicProxy

后端 未结 5 1389
一生所求
一生所求 2020-12-05 13:11

My questions is related to this post Intercept the call to an async method using DynamicProxy

I want to implement interceptor that works with async methods that retu

5条回答
  •  时光说笑
    2020-12-05 14:12

    A better solution would be to use the dynamic keyword to bypass the compiler type checking and resolve the operation 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 continuation work for Task...
    }
    
    private static async Task InterceptAsync(Task task)
    {
        T result = await task.ConfigureAwait(false);
        // do the continuation work for Task...
        return result;
    }
    

提交回复
热议问题