2

I am getting an ObjectDisposedException (Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed) during lazy instantiation of an object injected via Autofac in an async ASP.NET Web API method.

This is the Web API method:

Lazy<PrintHubSender> _printHubSender;

public async void Print(Guid orderId)
{
    var order = await _orderNoSqlDbRepository.GetSingleAsync(o => o.Id == orderId);
    _printHubSender.Value.PrintOrder(order); // This triggers the exception
}

The Lazy instance is injected via Web API controller constructor. The Autofac registration is as follows:

Type hubSender = ...
containerBuilder.RegisterType(hubSender)
    .AsSelf()
    .PropertiesAutowired()
    .InstancePerRequest();

If the ASP.NET Web API method is not async the exception does not occur.

1 Answer 1

4

The Web API engine has no knowledge if a method is async or not because async is a compile-time concept.

What the engine knows is if a method returns a Task derived value or not.

With the exception of event handlers or any other API where the completion of the method call is not important, the async equivalent of void is Task as the async equivalent of T is Task<T>.

Try this:

public async Task Print(Guid orderId)
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.