HomeChallengesRepsProblemsLeaderboardTake a challenge

The scoped thing inside the singleton

A background worker takes a DbContext in its constructor and holds it for the life of the process. It works in development, survives review, and fails under load as one connection is shared by everything. Resolve the scope where the work happens instead.

Advanced20 min on the clock5 graded checks · 100 pointsResources and ConcurrencyPro
Graded by reading your code against the checklist below.

What you build

  • The singleton stops taking scoped services in its constructor
  • It takes IServiceScopeFactory instead
  • A scope is created per unit of work
  • The scoped service is resolved from that scope
  • The scope is disposed when the work finishes
  • Validation of scopes is switched on so this fails at startup, not in production

Done means

The worker holds nothing scoped, and every unit of work gets its own scope and its own context.

How it is graded

Published in full, before you start — every point is one of these and there is nothing else.

  1. The worker holds nothing scoped+30Giving resources back
  2. A scope is created per unit of work+25Giving resources back
  3. The context is resolved from the scope+20Giving resources back
  4. The scope is disposed with the work+15Giving resources back
  5. A captive dependency fails at startup+10Settings, not string literals

What it teaches

The rest of Resources and Concurrency