Path: redb-route/redb.Route.Cache/CacheStores.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Cache/CacheStores.cs ---- using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; namespace redb.Route.Cache; /// /// Resolves the store for a node: options and caches come from the context services first /// (UseCache, AddService), then from DI, then — for the in-process cache — a /// is created once per context and shared by every cache node. /// internal static class CacheStores { private static readonly object Sync = new(); public static RouteCacheOptions Options(IRouteContext context) => context.GetService() ?? context.GetServiceProvider()?.GetService() ?? new RouteCacheOptions(); public static ICacheStore Resolve(IRouteContext context, CacheProvider provider) { lock (Sync) { return provider == CacheProvider.Distributed ? Distributed(context) : Memory(context); } } /// The computations in progress on the store returns for the same provider. public static System.Collections.Concurrent.ConcurrentDictionary> Flights(IRouteContext context, CacheProvider provider) { lock (Sync) { if (context.GetService() is not { } flights) { flights = new CacheFlights(); context.AddService(typeof(CacheFlights), flights); } return flights.For(provider); } } private static ICacheStore Memory(IRouteContext context) { if (context.GetService() is { } existing) return existing; var hostCache = context.GetService() ?? context.GetServiceProvider()?.GetService(); if (hostCache is null) { var options = Options(context); hostCache = new MemoryCache(new MemoryCacheOptions { SizeLimit = options.MaxEntries }); context.AddService(typeof(IMemoryCache), hostCache); } var store = new MemoryCacheStore(hostCache); context.AddService(typeof(MemoryCacheStore), store); return store; } private static ICacheStore Distributed(IRouteContext context) { if (context.GetService() is { } existing) return existing; var cache = context.GetService() ?? context.GetServiceProvider()?.GetService() ?? throw new InvalidOperationException( "Cache: no IDistributedCache is registered. Add one in DI (services.AddStackExchangeRedisCache(...), " + "AddDistributedMemoryCache()) or on the context (context.AddService(typeof(IDistributedCache), cache))."); var store = new DistributedCacheStore(cache, context.GetService()); context.AddService(typeof(DistributedCacheStore), store); return store; } }