簡體   English   中英

具有Autofac的異步ASP.NET Web API方法中的ObjectDisposedException

[英]ObjectDisposedException in async ASP.NET Web API method with Autofac

在通過異步ASP.NET Web API方法通過Autofac注入的對象的延遲實例化期間,出現了ObjectDisposedException(無法解析實例並且無法從此LifetimeScope創建嵌套生命周期,因為它已經被處置)。

這是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
}

延遲實例是通過Web API控制器構造函數注入的。 Autofac注冊如下:

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

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

Web API引擎不知道方法是否async ,因為async是一個編譯時概念。

引擎知道的是方法是否返回Task派生值。

除了事件處理程序或方法調用的完成並不重要的任何其他API之外, voidasync等效項是Task ,而Tasync等效項是Task<T>

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM