我正在我的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;
}
...实际进行异步调用的函数如下所示:
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;
}
}
答案 0 :(得分:0)
这里:
var sendResponse = SendToKensci(requestObject, batch);
你没有等待SendToKensci
(返回Task
),所以有时在执行中 - 上下文被处理(因为你已经离开了SendToVendor
函数)