SB2055 SB2055 - 1 year ago 89
C# Question

Await is disposing DbContext - The ObjectContext instance has been disposed

I have the following in an

async
method that has an instance of
dbContext
passed into it:

var userIds = await GetUserIds(db);


With GetUserIds:

private async Task<List<int>> GetUserIds(AppContext db)
{
var items = await db.Items.Where(s => s.IsValid).Distinct().ToListAsync(); // simplified
return items;
}


But I get:


{"The ObjectContext instance has been disposed and can no longer be
used for operations that require a connection."}


I can force this to run by removing
await
and
ToListAsync
, but obviously that's just a bandaid. Why is my context getting disposed?

Answer Source

I suspect the caller of your GetUserIds method is disposing the context before the operation completes. Are you sure you're awaiting the returned Task before disposing the context?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download