I have this little sample of code:
public class ValueController : ApiController
{
private EstateContext _db;
public ValueController()
{
_db = new EstateContext();
}
[HttpPost]
public async void DoStuff(string id)
{
var entity = await _db.Estates.FindAsync(id); //now our method goes out and Dispose method is calling
//returns here after disposing
_db.SaveChanges(); // _db is disposed
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_db.Dispose();
}
}
Every ApiController/Controller implements IDisposable interface. So in the Dispose method I want to free up any resources such as DbContext. But if async is used, this Dispose method calls at first occurrence of await. So after await I have DbContext already disposed. So what is the best way to dispose EF Contexts when async is used? It turns out that it is not possible to rely on Dispose method in controller?
async void? That seems like a bad idea...