5

我正在使用 Ninject Interceptor 以便在调用实际方法之前和之后执行一些任务,但我需要这些操作是异步的。我看了一下下面的文章making-ninject-interceptors-work-with-async-methods并实现了异步部分,但现在我错过了最后一篇,那就是等待/非阻塞等待任务完成在拦截方法中。

  • 我不能使用等待,因为我希望这是异步非阻塞操作

    /// <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;
     }
    
  • 我什至尝试将异步放在此方法上,但我仍然遇到问题,可能是因为这是一个无效方法

    /// <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);
    }
    

有没有办法让这个真正的异步方法?

4

1 回答 1

2

我被迫破解了这个问题,并且我在Ninject.Extensions.Interception中更改了一些代码以允许async/await

我刚刚开始测试代码,到目前为止,在调用Proceed之前等待似乎是有效的。我不能 100% 确定一切都按预期工作,因为我需要更多时间来玩这个,所以请随时检查实现,如果你发现错误或有建议,请回复我。

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

重要- 此解决方案仅适用于 LinFu DynamicProxy,因为 LinFu 以可用于允许异步等待的方式生成代理类。

注意:同样,这个解决方案是一个“hack”,而不是完整的异步拦截实现。

问候

于 2013-07-22T14:12:41.310 回答