Observer lifetime mismatch in DI: a scoped subscriber to a singleton subject (event and IOptionsMonitor.OnChange) stays reachable through the delegate invocation list; proving it with dotnet-counters, two dotnet-gcdump snapshots and paths to root; fixing it with IDisposable unsubscription the container calls, moving subscriptions to singletons, lambda pitfalls, weak references, and a WeakReference regression test.
It's an Observer lifetime mismatch. The singleton PriceFeed holds every subscriber in its event's invocation list (a strong reference through each delegate's Target), so each request's PriceDisplayService stays reachable long after the request ends. The ignored IDisposable from IOptionsMonitor.OnChange does the same thing.
To prove it: dotnet-counters shows GC heap and gen 2 size climbing without returning to baseline; two dotnet-gcdump snapshots show the PriceDisplayService count growing, with a path to root through PriceFeed → EventHandler → the service.
The fix: unsubscribe in Dispose (the container disposes scoped services at the end of the request), dispose the OnChange token, or better, move the subscription into a singleton that caches the latest price. The trade-off is that per-request subscriptions are almost never what you want; align observer and subject lifetimes.
"The shape of the graph tells you a lot: steady growth with every request, never released by gen 2 collections, means something long-lived is holding request-scoped objects. Here it's the Observer pattern with mismatched lifetimes.
PriceFeedis a singleton. When a scopedPriceDisplayServicedoesfeed.PriceChanged += OnPriceChangedin its constructor, the feed's delegate now holds a reference to that service through the delegate'sTarget. The request ends, the scope ends, but the feed still points at the service, so the GC can't collect it, or anything it references: itsDbContext, its logger scope, the user's data. One leaked object per request at [~2,000] requests an hour is how you get 200 MB a day.IOptionsMonitor.OnChangeis the same pattern: it returns anIDisposableand if you discard it, the monitor keeps your callback, and the closure keepsthis.To prove it, I'd first watch
dotnet-counters monitor -p <pid> --counters System.Runtimeand confirm GC heap size and gen 2 size climb and don't drop after full collections, which rules out normal gen 0 churn. Then I'd take twodotnet-gcdump collectsnapshots ten minutes apart, open them in Visual Studio or PerfView and diff them. The type with a growing count isPriceDisplayService, and 'paths to root' showsPriceFeed→EventHandler<PriceChanged>→ the invocation list →PriceDisplayService. That's the proof, and it takes about fifteen minutes in a test environment under load.For the fix, the quick one is to implement
IDisposable, unsubscribe with-=and dispose theOnChangetoken. The container disposes scoped services it created when the request scope ends, so that's enough. But the real question is why a per-request object is subscribing to a feed at all. Usually the right design is a singleton that owns the subscription and caches the latest price, and the scoped service just reads it. The mistake I see is subscribing with a lambda:feed.PriceChanged += (s, e) => ...can't be removed with-=and a new lambda, because it's a different delegate. Every+=needs an owner with the same lifetime as the publisher, or a-=that is guaranteed to run."
| Step | Tool | What you're looking for |
|---|---|---|
| 1. Confirm a managed leak | dotnet-counters monitor --counters System.Runtime |
GC heap size and gen 2 size rising after each gen 2 GC |
| 2. Find what grows | dotnet-gcdump collect -p <pid> twice, diff in Visual Studio or PerfView |
Instance count of PriceDisplayService (and what it holds) increasing |
| 3. Find who holds it | Paths to root in the dump | PriceFeed → EventHandler<T> → invocation list → service |
| 4. Confirm in production | Application Insights memory metrics vs request count | Growth proportional to requests, reset on recycle |
| Fix | How | When |
|---|---|---|
| Move the subscription to a singleton | Singleton PriceCache subscribes once and stores the latest value |
The scoped class only needs the current value |
Unsubscribe in Dispose |
IDisposable with -= and _optionsToken?.Dispose() |
The per-scope subscription is genuinely needed |
| Keep the delegate | Store the handler in a field so -= removes the same delegate |
You must subscribe with a lambda |
| Weak subscription | Publisher holds WeakReference to subscribers |
Third-party or plug-in subscribers you can't control |
A quote API leaked about 200 MB a day and was being recycled nightly by an App Service rule. Two gcdumps showed roughly 45,000 live PriceDisplayService instances after a day, each holding a DbContext. Moving the subscription into a singleton cache flattened the gen 2 heap at about 180 MB, removed the nightly recycle, and cut p99 latency by 30% because gen 2 collections dropped from dozens an hour to a handful.
Checks whether the candidate can connect the Observer pattern to DI lifetimes, prove a managed leak with the right tools and fix it at the design level.
Green flags
Target.dotnet-counters then two diffed dotnet-gcdump snapshots and paths to root.-= trap and the OnChange token.Red flags
GC.Collect.Root (static / DI root provider)
└─▶ PriceFeed (singleton)
└─▶ PriceChanged : EventHandler<PriceChanged> (multicast delegate)
└─▶ invocation list
├─▶ delegate { Target = PriceDisplayService#1, Method = OnPriceChanged }
├─▶ delegate { Target = PriceDisplayService#2, ... }
└─▶ ... one per request
The GC collects only what is unreachable from roots. A singleton is rooted by the root service provider for the life of the app, so everything its event references is reachable. Each += creates a new delegate whose Target is the subscriber instance. Nothing about the scope ending removes that edge.
IOptionsMonitor.OnChange is the same patternOnChange(listener) adds the listener to the monitor's list and returns an IDisposable? that removes it. The monitor is a singleton, and a lambda that uses instance members captures this. Discarding the token leaks the subscriber exactly like an event, and the callback keeps running against an object whose DbContext has already been disposed, which can surface as ObjectDisposedException in logs long after the request.
IDisposable scoped and transient services it created when the scope ends. That is your hook for -=.Dispose, it's disposed and still reachable.IDisposable services resolved from the root provider are tracked until the app shuts down: a second, related leak to check for.dotnet-counters: watch GC Heap Size, Gen 2 Size, Gen 2 GC Count and % Time in GC. A sawtooth that returns to the same floor is healthy; a rising floor is a leak.dotnet-gcdump captures the managed object graph with only a short pause (it triggers a gen 2 GC), small enough to take in production carefully. Diff two snapshots and sort by count delta. Event leaks show up as your subscriber type plus delegate types (EventHandler<T>, closure classes like <>c__DisplayClass).dotnet-dump plus dumpheap -stat and gcroot <address> gives the same answer from a full dump when you need native memory too.-=feed.PriceChanged += (s, e) => Update(e); // delegate A
feed.PriceChanged -= (s, e) => Update(e); // delegate B: not equal to A, nothing removed
Delegate equality compares target and method. Two lambdas compile to different methods (or a new closure instance), so removal silently does nothing. Store the handler in a field, use a method group, or use an API that returns an IDisposable.
A weak event holds the subscriber through a WeakReference<T> so the subscriber can be collected without unsubscribing. WPF has WeakEventManager; there is no general-purpose server-side equivalent in the BCL, so you write a small one or use a library. Weak events cost an extra allocation and a dead-reference sweep, and they hide lifetime bugs rather than fix them, so I keep them for plug-in style cases where I don't control subscribers.
bombardier or k6. Watch dotnet-counters.dotnet-gcdump snapshots, diff them, and follow the path to root to the event.IDisposable with -=, rerun, and confirm the gen 2 floor stays flat.GetInvocationList().Length.Dispose.Before: a scoped service subscribes to a singleton in its constructor and never lets go.
namespace Quotes;
using Microsoft.Extensions.Options;
public sealed record PriceChanged(string Sku, decimal Price);
public sealed class DisplayOptions { public int DecimalPlaces { get; set; } = 2; }
public sealed class PriceFeed // registered as a singleton
{
public event EventHandler<PriceChanged>? PriceChanged;
public void Publish(string sku, decimal price) => PriceChanged?.Invoke(this, new PriceChanged(sku, price));
}
// LEAKS: one instance per request stays reachable from the singleton forever
public sealed class LeakyPriceDisplayService
{
private decimal _last;
private int _decimals;
public LeakyPriceDisplayService(PriceFeed feed, IOptionsMonitor<DisplayOptions> options)
{
feed.PriceChanged += (_, e) => _last = e.Price; // lambda captures this; can't be removed
options.OnChange(o => _decimals = o.DecimalPlaces); // IDisposable discarded
_decimals = options.CurrentValue.DecimalPlaces;
}
public string Format() => Math.Round(_last, _decimals).ToString();
}
Fix 1: unsubscribe deterministically; the container calls Dispose when the request scope ends.
namespace Quotes;
using Microsoft.Extensions.Options;
public sealed class PriceDisplayService : IDisposable
{
private readonly PriceFeed _feed;
private readonly IDisposable? _optionsSubscription;
private decimal _last;
private int _decimals;
public PriceDisplayService(PriceFeed feed, IOptionsMonitor<DisplayOptions> options)
{
_feed = feed;
_feed.PriceChanged += OnPriceChanged; // method group: -= removes the same delegate
_optionsSubscription = options.OnChange(o => _decimals = o.DecimalPlaces);
_decimals = options.CurrentValue.DecimalPlaces;
}
private void OnPriceChanged(object? sender, PriceChanged e) => _last = e.Price;
public string Format() => Math.Round(_last, _decimals).ToString();
public void Dispose()
{
_feed.PriceChanged -= OnPriceChanged;
_optionsSubscription?.Dispose();
}
}
Fix 2 (preferred): one subscription, owned by a singleton with the same lifetime as the feed.
namespace Quotes;
using System.Collections.Concurrent;
public sealed class PriceCache : IDisposable // singleton: subscribes once for the life of the app
{
private readonly PriceFeed _feed;
private readonly ConcurrentDictionary<string, decimal> _latest = new();
public PriceCache(PriceFeed feed)
{
_feed = feed;
_feed.PriceChanged += OnPriceChanged;
}
private void OnPriceChanged(object? sender, PriceChanged e) => _latest[e.Sku] = e.Price;
public decimal? Get(string sku) => _latest.TryGetValue(sku, out var p) ? p : null;
public void Dispose() => _feed.PriceChanged -= OnPriceChanged;
}
// Scoped consumers just read; they never subscribe
public sealed class QuoteService(PriceCache cache)
{
public decimal? PriceFor(string sku) => cache.Get(sku);
}
// Program.cs
// builder.Services.AddSingleton<PriceFeed>();
// builder.Services.AddSingleton<PriceCache>();
// builder.Services.AddScoped<QuoteService>();
Regression test: prove the subscriber is collectable after its scope ends.
namespace Quotes.Tests;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.DependencyInjection;
public class PriceDisplayServiceLeakTests
{
[Fact]
public void Subscriber_is_collectable_after_scope_disposal()
{
var services = new ServiceCollection();
services.AddSingleton<PriceFeed>();
services.AddOptions<DisplayOptions>();
services.AddScoped<PriceDisplayService>();
using var root = services.BuildServiceProvider();
WeakReference weak = ResolveInScope(root); // separate method so no local keeps it alive
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.False(weak.IsAlive);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static WeakReference ResolveInScope(IServiceProvider root)
{
using var scope = root.CreateScope();
return new WeakReference(scope.ServiceProvider.GetRequiredService<PriceDisplayService>());
}
}
Dispose, or move the subscription into a singleton.IDisposable returned by IOptionsMonitor<T>.OnChange. Why it is wrong: The monitor keeps the callback and its captured this for the life of the app. Instead: Store the token and dispose it with the owner, or subscribe only from singletons.-= removes nothing. Instead: Use a method group or keep the delegate in a field.Dispose only does what you write in it; the publisher still references the object. Instead: Put -= in Dispose and test it.dotnet-gcdump snapshots under steady load and diff instance counts.Event leaks in services are almost always a design smell before they're a memory bug: a short-lived object is reacting to a long-lived stream. The fix that lasts is aligning lifetimes, so the long-lived thing owns the subscription and short-lived things read state. Deterministic Dispose is the second line, and a WeakReference test makes the rule enforceable.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Singleton owns subscription, caches state | Scoped code only needs the latest value | One shared cache to make thread-safe | Each scope needs its own stream of events |
IDisposable + -= in the subscriber |
Per-scope subscription is genuinely needed | Must remember every += |
Subscriber lifetime isn't controlled by the container |
IObservable<T> / OnChange token |
API returns a subscription object | Token must be stored and disposed | Fire-and-forget subscriptions |
| Weak events | Plug-ins or third-party subscribers | Extra allocations, hidden lifetimes | Your own code where you control lifetimes |
Measure the fix the same way you found it: the gen 2 floor in dotnet-counters should go flat under the same load, and the diffed instance count should stay near the number of in-flight requests.
The convention is EventHandler<TEventArgs> with object? sender and an immutable args object, EventArgs.Empty when there is no data, and a protected virtual OnXxx method that raises it. The big production risk is leaks: the publisher's delegate holds a strong reference to every subscriber, so a singleton or static publisher keeps short-lived subscribers alive forever. I find them with a heap dump and gcroot, which shows the path through the event's delegate, and fix them by unsubscribing in Dispose or using a weak event. Async handlers are async void, so I keep them thin and catch everything inside.
A closure is a lambda or local function plus the variables it captures. The compiler moves those variables into fields of a hidden display class, so the method and the lambda share the same variable. That's why capture is by variable, not by value. In a for loop all lambdas share one loop variable, while foreach gets a fresh one per iteration since C# 5. Every lambda in a scope shares one display class, and capturing this keeps the whole object alive, which can leak memory through timers and caches. In hot paths I use static lambdas with explicit state.
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
How to tell it (STAR)
**S:** At [company], our quote API's memory climbed about 200 MB a day and we were hiding it with a nightly recycle. **T:** I was asked to find the cause and remove the recycle. **A:** I reproduced it in staging under load, used `dotnet-counters` to confirm the gen 2 floor was rising, then diffed two `dotnet-gcdump` snapshots and followed the path to root: a singleton price feed's event was holding every request's `PriceDisplayService`, plus an `IOptionsMonitor.OnChange` closure. I moved the subscription into a singleton cache and added a WeakReference test. **R:** Memory flattened at about [180 MB], we removed the recycle, and p99 latency dropped by [30%] because gen 2 collections nearly disappeared.
Last updated 18 Nov 2026.