I am trying to build a Http API By C#. After returning the HTTP Response, I need to do some works and then update the database in the background.
However, I guess the DBContext instance is disposed automatically after the returning the API response, therefore, this error shows up:
“System.ObjectDisposedException: ‘Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application”
Here is my Code:
public async Task<DBmodel> GetAttachmentsListById(Guid Id, bool RequestSync)
{
var target = await Repository.GetDBmodelById(Id);
if (target != null)
{
if (RequestSync)
{
SyncAttachment(target);
}
if (target != null)
{
return DBmodel
}
}
return null!;
}
public void SyncAttachment(DBmodel target)
{
_serviceProvider = serviceProvider;
var executeScope = _serviceProvider.CreateScope();
var ServiceProvider = executeScope.ServiceProvider;
var repository = ServiceProvider.GetRequiredService<Repository>();
Action a = async () =>
{
ExternalClient Client = new ExternalClient();
var ExternalResult = await //Get External Information
if (//NeedUpdate)
{
foreach (var x in ExternalResult )
{
var model = new DBmodel;
model = ExternalResult;
await repository.UpDateDBmodel(att);//Exception Occurs Here
}
}
};
Task task1 = Task.Factory.StartNew(a);
task1.ContinueWith( c =>
{
executeScope.Dispose();
});
}