Path: redb-route/redb.Route.Cache/CacheRouteDefinitionExtensions.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/CacheRouteDefinitionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using redb.Route.Abstractions;
using redb.Route.Extensions;
namespace redb.Route.Cache;
/// DSL entry points and registration of the cache EIP.
public static class CacheRouteDefinitionExtensions
{
///
/// Opens a caching scope keyed by a route-language template ("customer-${header.customerId}").
/// On a hit the inner steps are skipped and the cached body is the message; on a miss they run and
/// the result is stored for . Close with EndCache().
///
public static CacheDefinition Cache(this IRouteDefinition route, string keyTemplate, TimeSpan? ttl = null)
=> Cache(route, CacheDefinition.KeyFromTemplate(keyTemplate), ttl);
/// Opens a caching scope with a key computed by .
public static CacheDefinition Cache(this IRouteDefinition route, Func key, TimeSpan? ttl = null)
{
ArgumentNullException.ThrowIfNull(route);
var definition = new CacheDefinition(key, ttl) { Parent = route };
route.Outputs.Add(definition); // the public tree API, identical to ProcessorDefinition.AddOutput
return definition;
}
/// Registers options and the cache: component on a context built without DI.
public static IRouteContext UseCache(this IRouteContext context, Action? configure = null)
{
ArgumentNullException.ThrowIfNull(context);
var options = new RouteCacheOptions();
configure?.Invoke(options);
context.AddService(typeof(RouteCacheOptions), options);
if (!context.GetComponentNames().Contains("cache", StringComparer.OrdinalIgnoreCase))
context.AddComponent(new CacheComponent());
return context;
}
/// DI registration: options plus the cache: component on the hosted context.
public static IServiceCollection AddRedbRouteCache(this IServiceCollection services, Action? configure = null)
{
ArgumentNullException.ThrowIfNull(services);
var options = new RouteCacheOptions();
configure?.Invoke(options);
services.TryAddSingleton(options);
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}