Home > Enterprise >  EF Core - Do I have to have a "using" statement to have my context disposed?
EF Core - Do I have to have a "using" statement to have my context disposed?

Time:11-02

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...

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

Will the context be correctly disposed in this case?

CodePudding user response:

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!

  • Related