yield return statement inside a using() { } block Disposes before executing
When you call GetAllAnimals
it doesn't actually execute any code until you enumerate the returned IEnumerable in a foreach loop.
The dataContext is being disposed as soon as the wrapper method returns, before you enumerate the IEnumerable.
The simplest solution would be to make the wrapper method an iterator as well, like this:
public static IEnumerable<Animal> GetAllAnimals() {
using (AnimalDataContext dataContext = new AnimalDataContext()) {
foreach (var animalName in dataContext.GetAllAnimals()) {
yield return GetAnimal(animalName);
}
}
}
This way, the using statement will be compiled in the outer iterator, and it will only be disposed when the outer iterator is disposed.
Another solution would be to enumerate the IEnumerable in the wrapper. The simplest way to do that would be to return a List<Animal>
, like this:
public static IEnumerable<Animal> GetAllAnimals() {
using (AnimalDataContext dataContext = new AnimalDataContext()) {
return new List<Animal>(dataContext.GetAllAnimals());
}
}
Note that this loses the benefit of deferred execution, so it will get all of the animals even if you don't need them.
The reason for this is that the GetAllAnimals method doesn't return a colleciton of animals. It returns an enumerator that is capable of returning an animal at a time.
When you return the result from the GetAllAnimals call inside the using block, you just return the enumerator. The using block disposes the data context before the method exits, and at that point the enumerator have not yet read any animals at all. When you then try to use the enumerator, it can not get any animals from the data context.
A workaround is to make the GetAllAnimals method also create an enumerator. That way the using block will not be closed until you stop using that enumerator:
public static IEnumerable<Animal> GetAllAnimals() {
using(AnimalDataContext dataContext = new AnimalDataContext()) {
foreach (Animal animal in dataContext.GetAllAnimals()) {
yield return animal;
}
}
}