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

Who should call Dispose on IDisposable objects when passed into another object?

P.S.: I have posted a new answer (containing a simple set of rules who should call Dispose, and how to design an API that deals with IDisposable objects). While the present answer contains valuable ideas, I have come to believe that its main suggestion often won’t work in practice: Hiding away IDisposable objects in “coarser-grained” … Read more

C# Linq-to-Sql – Should DataContext be disposed using IDisposable

Unlike most types which implement IDisposable, DataContext doesn’t really need disposing – at least not in most cases. I asked Matt Warren about this design decision, and here was his response: There are a few reasons we implemented IDisposable: If application logic needs to hold onto an entity beyond when the DataContext is expected to … 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

What happens if i return before the end of using statement? Will the dispose be called?

Yes, Dispose will be called. It’s called as soon as the execution leaves the scope of the using block, regardless of what means it took to leave the block, be it the end of execution of the block, a return statement, or an exception. As @Noldorin correctly points out, using a using block in code … Read more