Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

EF Core – Do I have to have a "using" statement to have my context disposed?

Suppose my class injects a DbContextFactory, then I can write a method like this…

private async Task<List<Device>> GetDevices() {
  await using AppDbContext ctx = await ContextFactory.CreateDbContextAsync();
  return await ctx.Devices.ToListAsync();
}

If I understand correctly, then as I create the context with a using, then it will be disposed of when the method ends.

Suppose I rewrite my method as follows…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private async Task<List<Device>> GetDevices() =>
  await (await ContextFactory.CreateDbContextAsync()).Devices.ToListAsync();

Will the context be correctly disposed in this case?

>Solution :

No you don’t have to dispose it. See this article for more information: https://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/

Quoting from the article:

The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed. E.g. when you execute a query and iterate over query results using "foreach", the call to IEnumerable.GetEnumerator() will cause the connection to be opened, and when later there are no more results available, "foreach" will take care of calling Dispose on the enumerator, which will close the connection. In a similar way, a call to DbContext.SaveChanges() will open the connection before sending changes to the database and will close it before returning.
Given this default behavior, in many real-world cases it is harmless to leave the context without disposing it and just rely on garbage collection.

Your rewritten function is fine!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading