Skip to main content

Anti-Pattern: Un-disposed Database Contexts (Resource Leak)

Description

Instantiating IDisposable resources, specifically DataContext or DbContext, without ensuring they are disposed. This commonly happens when new WEPV2DataContext() is called without a using block.

Impact

  • Stability: Database connection pool exhaustion ("Max Pool Size Reached").
  • Performance: Memory leaks as the Context and its tracked entities remain in memory until Finalized by GC.
  • Data Integrity: Contexts kept alive too long may hold stale data.

Detection

Search for constructors of context classes not wrapped in using.

# Forensic Grep: Find "new DataContext" NOT preceded by "using"
grep -r "new WEPV2DataContext" . | grep -v "using"
// ❌ BAD: Context created but never disposed explicitly
public void UpdateUser(int id) {
WEPV2DataContext db = new WEPV2DataContext();
var user = db.Users.Find(id);
// ...
}

Refactoring

Always wrap transient contexts in a using statement. See Performance Stabilization Pillar 5: DbContext Integrity.

// ✅ GOOD: Guaranteed disposal even if exceptions occur
public void UpdateUser(int id) {
using (WEPV2DataContext db = new WEPV2DataContext()) {
var user = db.Users.Find(id);
// ...
}
}

[!NOTE] If the Context is injected via Dependency Injection (DI) with PerRequest lifetime, explicit disposal in the application code is not required (the container handles it). However, WepNG_MVC often instantiates contexts manually.

2026 Audit Findings

  • Occurrences: > 850 instances of new WEPV2DataContext().
  • Severity: CRITICAL
  • Analysis: The vast majority are not wrapped in using.
  • Key Locations:
    • SkylinkController.cs
    • ZohoController.cs
    • RegisterController.cs