1
我在WebAPI應用程序的業務層內進行PostAsync調用。依賴注入庫模式對象在異步調用後處理
使用AutoFac我建立我的綁定是這樣的:
builder.RegisterGeneric(typeof(SqlServerRepository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
builder.RegisterType<WspSQLDbContext>()
.As<DbContext>()
.InstancePerLifetimeScope();
存儲庫注入到控制器:
public KenSciConnector(log4net.ILog logger, IRepository<KenSciBatch> kensciBatchRepository) {
_logger = logger;
_kensciBatchRepository = kensciBatchRepository;
}
這使得調用異步函數的功能是這樣的:
public Response SendToVendor(Observation observation) {
Response batchingResponse;
// some logic
var sendResponse = SendToKensci(requestObject, batch);
return batchingResponse;
}
...實際上使異步調用廁所的功能K類似於這樣:
private async Task<Response> SendToKensci(KenSciRequest requestObject, KenSciBatch kenSciBatch) {
var response = new Response();
try {
var httpClient = new HttpClient();
await httpClient
.PostAsync(httpClient.BaseAddress, new StringContent(seralizedObject, Encoding.UTF8, "application/json"))
.ContinueWith((requestTask) => UpdateBatch(requestTask, kenSciBatch));
} catch (Exception e) {
// some logic
return response;
}
// some logic
return response;
}
在回調函數,當我嘗試更新,我得到了DbContext
已被釋放異常。
private void UpdateBatch(Task<HttpResponseMessage> requestTask, KenSciBatch kenSciBatch) {
try {
if (requestTask.Result.StatusCode == HttpStatusCode.OK) {
kenSciBatch.Status = BatchStatus.Sent;
_kensciBatchRepository.Update(kenSciBatch);
}
} catch (Exception ex) {
throw ex;
}
}
是的,這是問題所在。把它當作答案。 –