C# › Dependency Injection & IoC Principles

How do you correctly and safely resolve a Scoped service from within a Singleton service using IServiceScopeFactory, avoiding the captive dependency problem?

Advanced

Answer

Inject IServiceScopeFactory (which is itself safely Singleton-lifetime) into the Singleton, and CREATE A NEW SCOPE explicitly each time you need to use a Scoped service — resolving the Scoped dependency from within that fresh, short-lived scope (and disposing it afterward) rather than injecting it directly into the Singleton's constructor.
public class BackgroundWorker : IHostedService {
  private readonly IServiceScopeFactory _scopeFactory;
  public BackgroundWorker(IServiceScopeFactory scopeFactory) { _scopeFactory = scopeFactory; }

  public async Task DoWorkAsync() {
    using var scope = _scopeFactory.CreateScope(); // fresh scope, correctly short-lived
    var db = scope.ServiceProvider.GetRequiredService<IDbContext>();
    await db.SaveChangesAsync();
  } // scope (and the Scoped service within it) disposed here
}
Real-world example Correctly accessing a Scoped Entity Framework DbContext from within a long-lived background/hosted service in ASP.NET Core.

Common follow-ups: Why must the scope specifically be created and disposed PER OPERATION, rather than once at the Singleton's construction time?