garryp
garryp

Reputation: 5776

Async/Await with Microsoft Unity

I have a project that uses Microsoft Unity and Web API 2. It works great and there are no problems with it. However when I try to use 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);
}

I get a ResolutionFailedException with this message:

Exception is:

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.

The ApiPlaceOrder is managed using UnityHierarchicalDependencyResolver.

The code works fine when async/await is not used.

Any ideas how to get Unity to play nice with async/await?

I've stripped the code for _apiPlaceOrder.Save(...) right back to this to try and isolate the problem and I still get the same issue:

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

Upvotes: 2

Views: 2140

Answers (1)

TylerOhlsen
TylerOhlsen

Reputation: 5578

You will get this error when you are using PerRequestLifetimeManager in the Unity.Mvc project and HttpContext.Current is null. That will occur when you are no longer on the originating thread of the http request.

Check your code for any occurrences of await fooTask.ConfigureAwait(false) or something that is creating a new thread or acquiring a thread from the thread pool. Hook up a debugger and put HttpContext.Current in your watch window and step through your code until that property switches to null.

Upvotes: 1

Related Questions