Gotcha returning the resource which you are disposing
suggest changeThe following is a bad idea because it would dispose the db variable before returning it.
public IDBContext GetDBContext()
{
using (var db = new DBContext())
{
return db;
}
}
This can also create more subtle mistakes:
public IEnumerable<Person> GetPeople(int age)
{
using (var db = new DBContext())
{
return db.Persons.Where(p => p.Age == age);
}
}
This looks ok, but the catch is that the LINQ expression evaluation is lazy, and will possibly only be executed later when the underlying DBContext has already been disposed.
The expression is not evaluated before the using block ends. One solution that still uses using is to enumerate immediately with ToList, ToArray, or another method that walks the results. Entity Framework also offers ToListAsync and ToArrayAsync.
The evaluated example:
public IEnumerable<Person> GetPeople(int age)
{
using (var db = new DBContext())
{
return db.Persons.Where(p => p.Age == age).ToList();
}
}
It is important to note, though, that by calling ToList() or ToArray(), the expression will be eagerly evaluated, meaning that all the persons with the specified age will be loaded to memory even if you do not iterate on them.