Repository navigation
Description
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
When AddStackExchangeRedisCache is configured with RedisCacheOptions.ConnectionMultiplexerFactory (a shared IConnectionMultiplexer — the exact pattern that Aspire.StackExchange.Redis.DistributedCaching wires up), the unkeyed HybridCache singleton is materialized twice in the same ServiceProvider: constructor-injected consumers receive one instance, GetService<HybridCache>() callers (including minimal-API parameter binding) receive another.
Both instances share the same IDistributedCache backend, so all data operations behave identically and the duplication is invisible — except for tag invalidation: each DefaultHybridCache keeps its tag-invalidation timestamps in a per-instance in-process dictionary and reads the L2 tag entry only once. RemoveByTagAsync called on one instance is therefore never observed by the other, so tag invalidation silently stops working across injection paths.
Root cause chain
DefaultHybridCache's constructor immediately kicks off an L2 read for the wildcard tag (_globalInvalidateTimestamp = ... SafeReadTagInvalidationAsync(TagSet.WildcardTag)in DefaultHybridCache.cs).- That read triggers the first Redis connect.
PrepareConnection→TryAddSuffixcallsIsHybridCacheActive(), whichRedisCacheImplimplements as_services.GetService<HybridCache>()(RedisCacheImpl.cs — note the existing comment "important: do not check for HybridCache here due to dependency - creates a cycle"; the cycle was moved out of the ctor but still fires during connect). - With
ConnectionMultiplexerFactoryreturning an already-completed task,ConnectSlowAsynccompletes synchronously — soGetService<HybridCache>()executes re-entrantly while theHybridCachesingleton is still inside its constructor.Microsoft.Extensions.DependencyInjectiondoes not detect this re-entrancy and manufactures a second instance instead.
Without the factory (plain options.Configuration), ConnectionMultiplexer.ConnectAsync yields at a real await, the constructor completes and publishes the singleton before TryAddSuffix runs, and everything stays consistent — which is why this only bites shared-multiplexer setups.
Expected Behavior
A singleton is created exactly once regardless of resolution path. At minimum, re-entrant resolution of a singleton under construction should throw (like circular constructor dependencies do) rather than silently duplicating state.
Steps To Reproduce
docker run -d -p 6379:6379 redis — then:
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.StackExchangeRedis;
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(o => o.InstanceName = "app:");
builder.Services.AddHybridCache();
// shared multiplexer — same wiring as Aspire.StackExchange.Redis.DistributedCaching
builder.Services.AddSingleton<IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect("localhost:6379"));
builder.Services.AddOptions<RedisCacheOptions>().Configure((RedisCacheOptions o, IServiceProvider sp) =>
o.ConnectionMultiplexerFactory = () => Task.FromResult(sp.GetRequiredService<IConnectionMultiplexer>()));
builder.Services.AddSingleton<CtorProbe>();
var app = builder.Build();
app.MapGet("/identity", (HybridCache viaParam, CtorProbe probe) =>
$"same={ReferenceEquals(probe.Cache, viaParam)}");
app.Run();
sealed class CtorProbe(HybridCache cache) { public HybridCache Cache => cache; }GET /identity → same=False (deterministic, every run). Remove the ConnectionMultiplexerFactory block → same=True.
Functional impact repro: SetAsync(key, value, tags: ["t"]) via the ctor-injected instance, then RemoveByTagAsync("t") via the parameter-injected one → the entry keeps being served as valid.
Exceptions (if any)
None — the failure is completely silent.
.NET Version
10.0.302
Anything else?
Package versions: Microsoft.Extensions.Caching.StackExchangeRedis 10.0.10, Microsoft.Extensions.Caching.Hybrid 10.8.0. Also reproduced through Aspire.StackExchange.Redis.DistributedCaching 13.4.6, which sets up exactly this ConnectionMultiplexerFactory pattern — so any Aspire + HybridCache application is affected out of the box.
Heap-dump evidence from a real application: dumpheap -type DefaultHybridCache shows two instances sharing the same RedisCacheImpl backend object and the same HybridCacheOptions object — one rooted in ConstructorCallSites, one in the ServiceProvider accessor cache.
Possible fixes, any one of which breaks the chain:
- (a)
RedisCacheImplresolvesHybridCachelazily/deferred instead of during connect; - (b)
DefaultHybridCachedefers the wildcard-tag read out of the constructor; - (c)
Microsoft.Extensions.DependencyInjectiondetects re-entrant singleton resolution.
Workaround for affected users: force the first Redis connect before HybridCache is ever resolved (e.g. a dummy IDistributedCache.GetAsync in an IHostedService registered before anything touches the cache).
Activity
svick commentedon Jul 29, 2026
I believe this was fixed by dotnet/runtime#124331.
@CaptainJackCode Can you check if using a recent .Net 11 preview resolves the issue for you?
cc: @dotnet/area-extensions-dependencyinjection
CaptainJackCode commentedon Jul 30, 2026
Thanks for the pointer @svick — confirmed, and verified twice. 👍
same=False); withMicrosoft.Extensions.DependencyInjection11.0.0-preview.6.26359.118 referenced directly it resolves to a single instance (same=True).HybridCache.RemoveByTagAsyncnow works correctly through both injection paths.So dotnet/runtime#124331 does fix this: the re-entrant
GetService<HybridCache>()fromRedisCacheImpl.TryAddSuffixhits the new cycle detection instead of silently manufacturing a second singleton, andTryAddSuffix's try/catch absorbs it (only side effect: theHClibrary-name suffix is skipped on that path — cosmetic).Given that on .NET 10 the failure mode is a silent duplicate singleton that breaks
RemoveByTagAsyncfor anyone combining HybridCache with a sharedIConnectionMultiplexer(the default wiring inAspire.StackExchange.Redis.DistributedCaching), would a backport of the detection to 10.0.x be considered? Otherwise feel free to close in favor of the runtime fix.rosebyte commentedon Jul 30, 2026
@CaptainJackCode, I'm happy the fix works for you, I'll propose backporting it to net10.0 and let you know when it could be available.
Add DI singleton reentrancy regression test (#131598)
rosebyte commentedon Aug 27, 2026
@CaptainJackCode, unfortunately, we can't backport the fix to a 10.0.x patch because there may be invalid dependency graphs that currently resolve only due to the bug allowing duplicate singleton registrations. We know of at least one such case in #67064.
@cincuranet, @Youssef1313, although not back portable, the issue is fixed on the runtime extensions level, shall we close it?
SlimShaggy commentedon Nov 18, 2026
Another workaround is to make the factory truly async: instead of
use
This lets the
DefaultHybridCacheconstructor complete before Redis connection is triggered, just like with plainoptions.Configuration.