我有一个使用 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.Current
为 null
时,您将收到此错误。当您不再位于 http 请求的原始线程上时,就会发生这种情况。
检查您的代码是否出现任何 await fooTask.ConfigureAwait(false)
或正在创建新线程或从线程池获取线程的内容。连接一个调试器并将 HttpContext.Current
放在您的监 window 口中并单步执行您的代码,直到该属性切换为 null
。
关于c# - 使用 Microsoft Unity 进行异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30212918/