Home > database >  Is the DbContext disposed when I do a ToList() in EF Core
Is the DbContext disposed when I do a ToList() in EF Core

Time:06-08

I read that, with EF Core, it is not obligated to use a using statement with the DBContext to dispose of it (or to call the de Dispose method directly). The garbage collector will do it. I also read that when you read the objects you've retrieved, they should dispose of too, but I am not sure if I understand correctly. Does it mean that if I do a toList() on a collection return by my DbContext, that my context will be disposed of at this moment? I have difficulties finding this specific answer on Google.

CodePudding user response:

The resource management of Entity Framework does not work in that manner. Entity Framework explicitly defines the lifetime when an instance created until the instance is disposed of. When the framework was developed, the fundamental purpose was to exist within a single unit-of-work which is why it is well suited for web applications, it can be used elsewhere- but the fundamental usage fit.

How you configure and scope your service will define the lifetime of the instance. But it should adhere to the following principals:

Typical unit-of-work would involve the creation of an instance, the tracking of the entity instances defined on the context, returned from query, added or attached to the context, change being made to the tracked entities. Then save those changes made and write them to the database. Then disposal of the instance.

So if you leverage a service such as:

public class CustomerAccountService : ICustomerAccountService
{
     private bool disposed = false;
     private readonly ICustomerRepository repository;

     public CustomerAccountService(ICustomerRepository repository) => this.repository = repository;

    // Additional logic would go here, including the implementation of the repository which will hold our DbContext.
}

When the CustomerAccountService is no longer scoped, then it would begin to clean dispose and clean up the Entity Framework instance as the lifetime has expired once the service. Keep in mind that the Dependency Injection container and your configuration will impact how this will be impacted. If you can, you should always add an IDispose that correctly reallocates those resources.

The documentation explicitly states:

It is very important to dispose the DbContext after use. This ensures both that any unmanaged resources are freed, and that any events or other hooks are unregistered so as to prevent memory leaks in case the instance remains referenced.

  • Related