C# / .NET Compendium PLEN
.NET / C# / SOLID, Clean Code, DI

IServiceScopeFactory - a full example

The problem we are solving

services.AddSingleton<INotificationManager, NotificationManager>();
services.AddScoped<IUserContext, UserContext>();

// BUG - Captive Dependency
public class NotificationManager : INotificationManager
{
    public NotificationManager(IUserContext userContext) { ... } // ❌
}

The solution: inject the factory, not the service itself

public class NotificationManager : INotificationManager
{
    private readonly IServiceScopeFactory _scopeFactory;

    // We inject a scope factory - this is safe for a Singleton,
    // bo IServiceScopeFactory sam jest zarejestrowany jako Singleton
    public NotificationManager(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    public async Task SendNotificationAsync(string message)
    {
        // Tworzymy NOWY scope w momencie, gdy faktycznie potrzebujemy
        // Scoped dependencies - not earlier, not "just in case"
        using (IServiceScope scope = _scopeFactory.CreateScope())
        {
            // We resolve IUserContext ONLY inside this scope
            var userContext = scope.ServiceProvider.GetRequiredService<IUserContext>();

            Console.WriteLine($"Sending a notification to: {userContext.CurrentUserName}");
            await SomeExternalService.SendAsync(userContext.CurrentUserName, message);
        }
        // After leaving using() - the scope and all of its Scoped/Transient
        // dependencies are released (Dispose)
    }
}

The key difference: instead of receiving IUserContext once in the constructor (and holding it "forever"), NotificationManager receives a factory which, on every method call, creates a fresh, temporary container with its own IUserContext. The scope lives only for the duration of the using block, so nothing gets "frozen".

What it looks like in practice with many dependencies

public class ReportGeneratorBackgroundService : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<ReportGeneratorBackgroundService> _logger;

    public ReportGeneratorBackgroundService(
        IServiceScopeFactory scopeFactory,
        ILogger<ReportGeneratorBackgroundService> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                // DbContext is Scoped - in a background Singleton
                // (BackgroundService) you couldn't normally inject it
                var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                var reportService = scope.ServiceProvider.GetRequiredService<IReportService>();

                var pendingOrders = await dbContext.Orders
                    .Where(o => !o.ReportGenerated)
                    .ToListAsync(stoppingToken);

                foreach (var order in pendingOrders)
                {
                    await reportService.GenerateAsync(order);
                }
            }

            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
        }
    }
}

This is a very common pattern - BackgroundService in .NET is always a Singleton, so if it needs a DbContext (Scoped), it always has to go through IServiceScopeFactory.

Registration - nothing extra to do

IServiceScopeFactory is automatically available in every IServiceCollection from Microsoft.Extensions.DependencyInjection - you don't need to register it manually.


What does "thread-safe" mean?

Thread-safe means the code works correctly when many threads execute it at the same time and touch the same data - without corrupting state, race conditions or unpredictable results.

An example of code that is NOT thread-safe

public class CounterService
{
    private int _count = 0;

    public void Increment()
    {
        _count++; // ⚠️ This looks like one operation, but it isn't!
    }

    public int GetCount() => _count;
}

_count++ is actually three separate steps: 1. Read the value of _count 2. Add 1 3. Write the result back to _count

If two threads do this at the same time:

Thread A: reads _count = 5
Thread B: reads _count = 5      (before A has written!)
Thread A: computes 5 + 1 = 6
Thread B: computes 5 + 1 = 6
Thread A: writes _count = 6
Thread B: writes _count = 6       ← overwrites thread A's result!

The effect: you called Increment() twice, and _count grew by only 1 instead of 2. This is a race condition - the result depends on "which thread gets there first", i.e. on chance/timing.

Why this matters specifically for a Singleton

If CounterService is registered as a Singleton:

services.AddSingleton<CounterService>();

...then all requests/threads in the whole application share the same instance and the same _count field. Under heavy traffic, when many requests arrive in parallel, this race condition will really happen - and only sporadically, hard to reproduce (a classic "heisenbug" - it works in the debugger, because the debugger slows execution down and masks the problem).

If CounterService were Transient or Scoped, every thread/request would have its own instance with its own _count - the problem wouldn't exist, because there is no shared state.

How to fix it - several approaches

1. lock - the simplest, but blocking

public class CounterService
{
    private readonly object _lock = new object();
    private int _count = 0;

    public void Increment()
    {
        lock (_lock)
        {
            _count++; // only one thread at a time can enter this block
        }
    }
}

2. Interlocked - for simple atomic operations, without locking

public class CounterService
{
    private int _count = 0;

    public void Increment()
    {
        Interlocked.Increment(ref _count); // atomowa operacja na poziomie CPU
    }

    public int GetCount() => Interlocked.CompareExchange(ref _count, 0, 0);
}

3. ConcurrentDictionary, ConcurrentQueue etc. - ready-made thread-safe collections

public class CacheService
{
    // instead of the plain Dictionary<K,V>, which is NOT thread-safe
    private readonly ConcurrentDictionary<string, User> _cache = new();

    public void Add(string key, User user) => _cache[key] = user;
    public User Get(string key) => _cache.TryGetValue(key, out var user) ? user : null;
}

A practical rule for Singletons

If a Singleton has mutable state (fields that change after creation) - it must be thread-safe. If it is stateless (immutable) or only reads data set once at startup - there is no problem.

// OK bez synchronizacji - stan ustawiony raz, tylko odczyt
public class AppConfig
{
    public string ApiUrl { get; }
    public AppConfig(IConfiguration config) => ApiUrl = config["ApiUrl"];
}

// REQUIRES synchronisation - the state changes while the app is running
public class RequestCounter
{
    private int _totalRequests; // ⚠️ mutable, many threads write at the same time
}

This is, by the way, a frequent interview question: "Why is DbContext in EF Core Scoped and not Singleton?" - and the answer is exactly this: DbContext is not thread-safe (it has an internal change tracker and transaction state), so if it were a Singleton, two parallel requests operating on the same DbContext would corrupt each other's state.

Buy me a coffee