制作Ninject拦截器';s Intercept方法是一种异步方法

本文关键字:方法 异步方法 一种 Intercept Ninject 制作 | 更新日期: 2023-09-27 18:22:22

我使用Ninject Interceptor是为了在实际方法被调用之前和之后执行一些任务,但我需要这些操作是异步的。我看了下面的文章,让ninject拦截器与异步方法一起工作,并实现了异步部分,但现在我缺少了最后一部分,那就是在Intercept方法中等待/非阻塞等待任务完成。

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

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

有没有一种方法可以让这个真正的async一直方法?

制作Ninject拦截器';s Intercept方法是一种异步方法

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

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

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

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

注意:同样,这个解决方案是一个"破解",而不是完全的异步拦截实现

问候