c# - 使用 Microsoft Unity 进行异步/等待

标签 c# .net asp.net-web-api async-await unity-container

我有一个使用 Microsoft Unity 和 Web API 2 的项目。它运行良好,没有任何问题。但是当我尝试使用 async/await

public async Task<IHttpActionResult> Post(PackageOrderDto dto)
{
    try
    {
        newOrderNumber = await _apiPlaceOrder.Save(dto));
    }
    catch (ApiValidationFailedException apiValidationFailedException)
    {
        return BadRequest(apiValidationFailedException);
    }
    return Ok("VF" + newOrderNumber);
}

我收到一个包含此消息的 ResolutionFailedException:

异常(exception)是:

InvalidOperationException - The PerRequestLifetimeManager can only be used in the context of an HTTP request. Possible causes for this error are using the lifetime manager on a non-ASP.NET application, or using it in a thread that is not associated with the appropriate synchronization context.

ApiPlaceOrder 使用 UnityHierarchicalDependencyResolver 进行管理。

当不使用 async/await 时,代码工作正常。

有什么想法可以让 Unity 与 async/await 配合得很好吗?

我已经剥离了 _apiPlaceOrder.Save(...) 的代码,试图找出问题所在,但我仍然遇到同样的问题:

public class ApiPlaceOrder
{
    public async Task<int> Save(PackageOrderDto dto)
    {
        await Task.Delay(10000);
        return 1;
    }
}

最佳答案

当您在 Unity.Mvc 项目中使用 PerRequestLifetimeManager 并且 HttpContext.Currentnull 时,您将收到此错误。当您不再位于 http 请求的原始线程上时,就会发生这种情况。

检查您的代码是否出现任何 await fooTask.ConfigureAwait(false) 或正在创建新线程或从线程池获取线程的内容。连接一个调试器并将 HttpContext.Current 放在您的监 window 口中并单步执行您的代码,直到该属性切换为 null

关于c# - 使用 Microsoft Unity 进行异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30212918/

相关文章:

c# - Paypal Api 没有重定向到 Express Checkout 第一次付款第二次工作正常

.net - 如何将 lync 与 Windows 窗体应用程序集成

.net - 反序列化时如何配置ServiceStack.Text JsonSerializer 属性名称

asp.net-web-api - WebApi - 传递值数组

asp.net - 为什么 Asp.NET WebApi 使用 ExceptionFilter 呈现 IIS 错误页面作为响应?

c# - 业务对象的公共(public)和内部接口(interface)模式

c# - 如何从音乐文件中读取样本?

c# - 尝试连接时,Azure Vault 中的 GetSecret 抛出 NullReferenceException

.net - 对于这个多线程问题该采取哪种方法?

c# - WebAPI StreamContent 与 PushStreamContent