When should one call DbContext.dispose()
with entity framework?
Is this imaginary method bad?
public static string GetName(string userId)
{
var context = new DomainDbContext();
var userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
context.Dispose();
return userName;
}
Is this better?
public static string GetName(string userId)
{
string userName;
using(var context = new DomainDbContext()) {
userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
context.Dispose();
}
return userName;
}
Is this even better, that is, should one NOT call context.Dispose() when using using()?
public static string GetName(string userId)
{
string userName;
using(var context = new DomainDbContext()) {
userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
}
return userName;
}
In fact this is two questions in one:
Dispose()
of a context?Answers:
1 a) Never when dependency injection is operational. The dependency container takes care of object life cycles.
1 b) When not using dependency injection, of using a context factory (for example, in Blazor applications), still never 1. You'd typically use a using
block, which is an implicit Dispose()
in a try-finally
block. A separate Dispose
statement can be missed when an exception occurs earlier. Also, in most common cases, not calling Dispose
at all (either implicitly or explicitly) isn't harmful because EF closes the database connection after each interaction with the database.
2 ) See e.g. Entity Framework 4 - lifespan/scope of context in a winform application. In short: lifespan should be "short", static context is bad.
1 As some people commented, an exception to this rule is when a context is part of a component that implements IDisposable
itself and shares its life cycle. In that case you'd call context.Dispose()
in the Dispose
method of the component. Unless, again, a DI container takes care of object life cycles.