c# - 使 Ninject 拦截器的拦截方法成为异步方法

标签 c# .net async-await ninject-interception

我正在使用 Ninject 拦截器,以便在调用实际方法之前和之后执行一些任务,但我需要这些操作是异步的。我看过下面的文章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;
     }
    
  • 我什至尝试将异步放在这个方法上,但我仍然遇到问题,可能是因为这是一个 void 方法

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

有没有办法让这个真正的异步方法一直存在?

最佳答案

我被迫想办法解决这个问题,我更改了 Ninject.Extensions.Interception 中的一些代码以允许 async/await

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

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

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

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

问候

关于c# - 使 Ninject 拦截器的拦截方法成为异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663808/

相关文章:

python - 异步 : [ERROR] Task was destroyed but it is pending

WPF 之上的 C# async/await Task<BitmaptImage> 问题

c# - 使用 C# 创建图表

c# - 如何按日、周、月自动发送邮件?

C# IL - 调用构造函数

.net - 响应式扩展与事件聚合器

c# - 如何在windows窗体上更快地画圆?

c# - 我将如何以编程方式访问此 WPF XAML 资源?

.net - 为客户提供 .NET 的替代方案

.net - IAsyncOperation 在 Windows 服务中等待 : "Type is defined in an assembly that is not referenced..."