Intercept async method that returns generic Task<> via DynamicProxy

后端 未结 5 1395
一生所求
一生所求 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:04

    The solutions from @Silas Reinagel and @thepirat000 didn't work for me, and I was not successful using Castle.Core.AsyncInterceptor solution from @James Skimming.

    In my case, I'm intercepting an async method returning Task, and it should execute "after invocation.Proceed() code" only if there was no exception during the invocation.Proceed(). At the end I used @James Skimming's code sample, so this solution works only for intercepting async methods returning Task and not Task:

    public void Intercept(IInvocation invocation)
    {
        _stepPriorInvocation();
    
        invocation.Proceed();
        Func continuation = async () =>
        {
            await (Task)invocation.ReturnValue;
    
            _stepAfterSuccessfulInvocation();
        };
    
        invocation.ReturnValue = continuation();
    
        void _stepPriorInvocation()
        {
        }
    
        void _stepAfterSuccessfulInvocation()
        {
        }
    }
    
    

提交回复
热议问题