Skip to content

Singleton HybridCache is created twice when RedisCache uses ConnectionMultiplexerFactory — re-entrant GetService<HybridCache>() during DefaultHybridCache construction breaks RemoveByTagAsync #67904

Open

Description

@CaptainJackCode

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

  1. DefaultHybridCache's constructor immediately kicks off an L2 read for the wildcard tag (_globalInvalidateTimestamp = ... SafeReadTagInvalidationAsync(TagSet.WildcardTag) in DefaultHybridCache.cs).
  2. That read triggers the first Redis connect. PrepareConnection → TryAddSuffix calls IsHybridCacheActive(), which RedisCacheImpl implements 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).
  3. With ConnectionMultiplexerFactory returning an already-completed task, ConnectSlowAsync completes synchronously — so GetService<HybridCache>() executes re-entrantly while the HybridCache singleton is still inside its constructor. Microsoft.Extensions.DependencyInjection does 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) RedisCacheImpl resolves HybridCache lazily/deferred instead of during connect;
  • (b) DefaultHybridCache defers the wildcard-tag read out of the constructor;
  • (c) Microsoft.Extensions.DependencyInjection detects 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

  1. added
    feature-caching
    area-middleware
    on Jul 21, 2026
  2. svick commented on Jul 29, 2026

    @svick
    Member

    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

  3. CaptainJackCode commented on Jul 30, 2026

    @CaptainJackCode
    Author

    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

    Thanks for the pointer @svick — confirmed, and verified twice. 👍

    1. Minimal repro (net10.0): with the inbox 10.0.x DI the singleton duplicates (same=False); with Microsoft.Extensions.DependencyInjection 11.0.0-preview.6.26359.118 referenced directly it resolves to a single instance (same=True).
    2. Real application: pinned the preview DI package across the solution, removed our warm-up workaround entirely — HybridCache.RemoveByTagAsync now works correctly through both injection paths.

    So dotnet/runtime#124331 does fix this: the re-entrant GetService<HybridCache>() from RedisCacheImpl.TryAddSuffix hits the new cycle detection instead of silently manufacturing a second singleton, and TryAddSuffix's try/catch absorbs it (only side effect: the HC library-name suffix is skipped on that path — cosmetic).

    Given that on .NET 10 the failure mode is a silent duplicate singleton that breaks RemoveByTagAsync for anyone combining HybridCache with a shared IConnectionMultiplexer (the default wiring in Aspire.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.

  4. rosebyte commented on Jul 30, 2026

    @rosebyte
    Member

    @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.

  5. rosebyte commented on Aug 27, 2026

    @rosebyte
    Member

    @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?

  6. removed their assignment
    on Aug 28, 2026
  7. added
    bug
    on Oct 23, 2026
  8. SlimShaggy commented on Nov 18, 2026

    @SlimShaggy

    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).

    Another workaround is to make the factory truly async: instead of

    o.ConnectionMultiplexerFactory = () => Task.FromResult(sp.GetRequiredService<IConnectionMultiplexer>()));
    

    use

    o.ConnectionMultiplexerFactory = async () =>
    {
        await Task.Yield();
        return sp.GetRequiredService<IConnectionMultiplexer>();
    };
    

    This lets the DefaultHybridCache constructor complete before Redis connection is triggered, just like with plain options.Configuration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-middlewarebugfeature-caching

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions