When are .NET Core dependency injected instances disposed?

The resolved objects have the same life-time/dispose cycle as their container, that’s unless you manually dispose the transient services in code using using statement or .Dispose() method. In ASP.NET Core you get a scoped container that’s instantiated per request and gets disposed at the end of the request. At this time, scoped and transient dependencies … Read more

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 … Read more