2016-01-23 71 views
2

在通過Autofac注入的對象的惰性實例化過程中,我得到一個ObjectDisposedException(實例無法解析並且嵌套生命期無法從此LifetimeScope中創建,因爲它已經處理完畢)一個異步的ASP.NET Web API方法。Autofac異步ASP.NET Web API方法中的ObjectDisposedException

這是Web API方法:

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 
} 

懶惰實例通過網絡API的控制器構造注入。 Autofac註冊如下:

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

如果ASP.NET Web API方法不是異步,則不會發生異常。

回答

4

如果方法是async,Web API引擎不知道,因爲async是編譯時的概念。

引擎知道的是如果方法返回Task派生值或不。

隨着事件處理程序的異常或任何其他API,其中方法調用的完成並不重要,所述async等效的voidTask作爲async等效的TTask<T>

試試這個:

public async Task Print(Guid orderId) 
{ 
    ... 
}