Making Ninject Interceptor's Intercept method an async method

1.3k views Asked by At

I'm using Ninject Interceptor in order do some tasks before and after the actual method gets called but I need these operations to be asynchronous. I have take a look at the following article making-ninject-interceptors-work-with-async-methods and implement that async part, but now I'm missing one last piece and that is waiting / non-blocking wait for task to complete in Intercept method.

  • I can't use wait because I want this to be asynchronous non-blocking operation

    /// <summary>
    /// Intercepts the specified invocation.
    /// </summary>
    /// <param name="invocation">The invocation to intercept.</param>
    public void Intercept(IInvocation invocation)
    {
        Task<bool> resultTask = InterceptAsync(invocation);
        if (resultTask.Exception != null)
            throw new Exception("Exception.", resultTask.Exception.InnerException);
    }
    
    
    /// <summary>
    /// Intercepts the specified invocation.
    /// </summary>
    /// <param name="invocation">The invocation to intercept.</param>
    protected async Task<bool> InterceptAsync(IMyInvocation invocation)
    {
        await BeforeInvokeAsync(invocation);
        if (!invocation.Cancel)
        {
            invocation.Proceed();
            await AfterInvokeAsync(invocation);
        }
        return true;
     }
    
  • I have even tried to put the async on this method and I still have problems, probably with the fact this is a void method

    /// <summary>
    /// Intercepts the specified invocation.
    /// </summary>
    /// <param name="invocation">The invocation to intercept.</param>
    public async void Intercept(IInvocation invocation)
    {
        Task<bool> resultTask = InterceptAsync(invocation);
        await resultTask;
        if (resultTask.Exception != null)
            throw new Exception("Exception.", resultTask.Exception.InnerException);
    }
    

Is there a way to make this real async all the way method ?

1

There are 1 answers

0
khorvat On

I have been forced to hack my way out of this issue and I have changed few bits of code inside Ninject.Extensions.Interception to allow async/await.

I have just started testing the code and so far it seems that awaiting before Proceed is called is working. I'm not 100% sure that everything is working as expected because I need more time to play with this, so feel free to check out the implementation and get back to me if you find bugs or have suggestions.

https://github.com/khorvat/ninject.extensions.interception

IMPORTANT - this solution works only with LinFu DynamicProxy as LinFu generates proxy classes in way that can be used to allow asynchronous waiting.

Note: Again this solution is a "hack" and not the full asynchronous interception implementation.

Regards