I've been doing a lot of reading around garbage collecting and and using IDisposable to handle connections via entity framework. I understand that I should be disposing of resources as soon as I'm done with them but I haven't seen a lot of good examples around when exactly that call should be made and where from and want to ensure I'm handling this correctly.
Let's say I'm returning a basic inventory list from a web API call. My assumption is I should call my dispose method immediately after I get the list. Is this correct? For example's sake let's look at the below method that lives in the service layer:
public class ServiceLayer
{
private InventoryContext _db = new InventoryContext();
public List<Inventory> GetFullInventoryList()
{
var inventoryList = _db.Inventory.ToList();
_db.Dispose();
return inventoryList;
}
public Inventory GetInventoryRecordById(int id)
{
var inventoryRecord = _db.Inventory
.Where(y => y.Id == id)
.First();
_db.Dispose();
return inventoryRecord;
}
}
Is this the correct way to dispose of resources? If not, when should it be called? If it is correct, but not the appropriate way, what is the appropriate way?
Thanks!
There are several options available, but all of them follow a common rule: the owner of the context (the one who creates it) should also dispose it.
You can:
Create your context in a service method and dispose it in the same method:
public List<Inventory> GetFullInventoryList()
{
using (var _db = new InventoryContext())
{
return _db.Inventory.ToList();
}
}
Create your context in your service class but then you would need to make the class IDisposable and implement the dispose pattern . This is more complicated, so only use it if you need to call multiple service methods that each work with the database.
Autofac
or Windsor
do this, assuming you call dispose on the container or its life scope). You can use PerWebRequest lifestyle for this.