Raas Masood Raas Masood - 10 months ago 72
C# Question

Dependency Injected Repository Pattern object gets disposed after asyn call

I am making a PostAsync call within the business layer of my WebAPI application.

Using AutoFac I am setting up my bindings like this:

builder.RegisterGeneric(typeof(SqlServerRepository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
builder.RegisterType<WspSQLDbContext>()
.As<DbContext>()
.InstancePerLifetimeScope();


The repository is injected into the controller:

public KenSciConnector(log4net.ILog logger, IRepository<KenSciBatch> kensciBatchRepository) {
_logger = logger;
_kensciBatchRepository = kensciBatchRepository;
}


The function which makes the call to the async function looks like this:

public Response SendToVendor(Observation observation) {
Response batchingResponse;
// some logic
var sendResponse = SendToKensci(requestObject, batch);
return batchingResponse;
}


...and the function which actually makes the async call look like this:

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;
}


In the callback function when I try to update, I get an exception that the
DbContext
has already been disposed.

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;
}
}

Evk Evk
Answer Source

Here:

var sendResponse = SendToKensci(requestObject, batch); 

you don't await SendToKensci (which returns Task), and so sometimes in the middle of it's execution - context is disposed (because you left SendToVendor function already)