Path: redb-route/redb.Route.Core/Extensions/RedbRouteExtensions.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.Core/Extensions/RedbRouteExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Route.Abstractions;
using redb.Route.Controllers;
namespace redb.Route.RedbCore.Extensions;
///
/// Extension methods for accessing from route pipeline.
/// Provides typed integration points: Process, SetBody, SetHeader with (IRedbService, IExchange).
/// When exchange has a DI scope (), a scoped
/// is resolved per exchange; otherwise falls back to the route context singleton.
///
public static class RedbRouteExtensions
{
// ── Context helpers ──────────────────────────────────────────────
private const string RegistryPrefix = "redb:";
private const string FactoryPrefix = "redb-factory:";
private const string ScopeCachePrefix = "__redb_scope:";
// Reserved cache key for the DEFAULT (unnamed) per-exchange redb scope. The '\0' suffix
// can never collide with a named instance ("__redb_scope:{name}") and is still disposed by
// Exchange.ReleaseScopes() (which drops every key starting with ScopeCachePrefix).
private const string DefaultScopeKey = ScopeCachePrefix + "\0";
///
/// Resolves the default from context service locator → DI fallback.
///
public static IRedbService GetRedbService(this IRouteContext context)
{
ArgumentNullException.ThrowIfNull(context);
return context.GetService()
?? context.GetServiceProvider()?.GetService(typeof(IRedbService)) as IRedbService
?? throw new InvalidOperationException(
"IRedbService is not registered. Call services.AddRedb() / services.AddRedbPro(), "
+ "or register a named instance via context.RegisterRedbService(name, instance).");
}
///
/// Resolves a named .
///
/// Scoping model for named instances:
/// Named IRedbService is stateful (like EF DbContext) and must NOT be shared across
/// concurrent exchanges. When is provided, a per-exchange
/// scoped instance is created from the registered
/// (placed in registry by TsakContextManager under "redb-factory:{name}" key).
/// The scope is cached in and auto-disposed when
/// the exchange completes ().
///
///
/// Resolution priority:
///
/// - Cached scope in exchange.Properties (same exchange, second call)
/// - New scope from factory in registry (first call with exchange)
/// - New scope opened from the registered instance through (first call with exchange,
/// no factory: a host outside Tsak whose instance was built through a container)
/// - Singleton fallback from registry (no exchange, or an instance built without a container)
///
///
/// Falls back to the default (unnamed) service if the name is null or empty.
///
/// Route context.
///
/// Registry name (e.g. "my-db" or "#my-db" — leading # is stripped automatically).
///
///
/// Current exchange for per-exchange scoping. When provided, the resolved service is
/// tied to the exchange lifecycle (thread-safe). Pass null for singleton fallback
/// (seed/diagnostics only — not safe under concurrency). Parallel code without an exchange opens a scope of its
/// own per call with .
///
public static IRedbService GetRedbService(this IRouteContext context, string name, IExchange? exchange = null)
{
ArgumentNullException.ThrowIfNull(context);
// Even when no name is supplied, prefer the per-exchange ServiceProvider so the
// resolved IRedbService is tied to the exchange's DI scope (per-request scope) and
// not captured as a captive singleton from the root provider — which would force all
// concurrent requests through a single NpgsqlConnection and surface as
// "A command is already in progress" / "connection is already in state 'Copy'".
if (string.IsNullOrEmpty(name))
return ResolveScopedRedb(context, exchange);
var cleanName = name.TrimStart('#');
// When exchange is provided, prefer per-exchange scoped instance (thread-safe).
if (exchange != null)
{
var cacheKey = ScopeCachePrefix + cleanName;
// 1. Already cached in this exchange?
if (exchange.Properties.TryGetValue(cacheKey, out var cached))
{
if (cached is ExchangeRedbScope own)
return own.Service;
if (cached is IServiceScope cachedScope)
return cachedScope.ServiceProvider.GetRequiredService();
}
// 2. Factory registered? Create a new scope and cache it.
if (context.GetFromRegistry(FactoryPrefix + cleanName) is { } factory)
{
var scope = factory.CreateScope();
exchange.Properties[cacheKey] = scope;
return scope.ServiceProvider.GetRequiredService();
}
// 3. No published factory: a host outside Tsak registered the instance itself. An instance built
// through a container opens a scope of the same database for this exchange, as the factory does.
if (context.GetFromRegistry(RegistryPrefix + cleanName) is { CanCreateScope: true } instance)
{
var redbScope = instance.CreateScope();
exchange.Properties[cacheKey] = new ExchangeRedbScope(redbScope); // disposed by Exchange.ReleaseScopes()
return redbScope.Service;
}
}
// 4. Singleton fallback: no exchange (start-up code), or an instance built without a container.
return context.GetFromRegistry(RegistryPrefix + cleanName)
?? throw new InvalidOperationException(
$"Named IRedbService '{name}' is not found in context registry. "
+ "Register it via context.RegisterRedbService(name, instance) or configure in Redb section.");
}
///
/// Registers a named in the context registry.
/// Business routes use this to provide their own redb instance (different DB, provider, etc.).
///
/// Route context.
/// Unique name for this redb instance (e.g. "orders-db").
/// The redb service instance to register.
public static IRouteContext RegisterRedbService(this IRouteContext context, string name, IRedbService redbService)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentNullException.ThrowIfNull(redbService);
context.AddToRegistry(RegistryPrefix + name.TrimStart('#'), redbService);
return context;
}
/// Whether a default resolves on , as finds it.
internal static bool IsDefaultRedbRegistered(IRouteContext context)
=> context.GetService() is not null
|| context.GetServiceProvider()?.GetService(typeof(IRedbService)) is IRedbService;
/// Whether the named instance is published on : a scope factory (Tsak) or a registered instance.
internal static bool IsNamedRedbRegistered(IRouteContext context, string name)
{
var cleanName = name.TrimStart('#');
return context.GetFromRegistry(FactoryPrefix + cleanName) is not null
|| context.GetFromRegistry(RegistryPrefix + cleanName) is not null;
}
///
/// Opens a scope with its own , for code that runs without an exchange and may run in
/// parallel: an observer, a background job, a store call made outside a route step. Every call opens a new scope,
/// so parallel callers never share a connection. The caller owns the scope and disposes it (await using).
///
/// Named ( set): the scope factory a host published for the name (Tsak does, one
/// per named instance), otherwise a scope opened from the instance registered with
/// (). Default (no name): a scope opened
/// from the service registered on the context, otherwise a scope of the context's service provider.
///
///
/// A service built without a DI container has no scope to open: the call throws
/// instead of handing out the shared instance, which is exactly the
/// contention this method exists to avoid. Single-threaded start-up code (scheme sync, seeding) keeps using
/// without an exchange.
///
///
/// A scope opened inside an ambient transaction takes part in it. Work that must survive the route's rollback
/// (an audit record, a budget counter) opens its scope under a suppressing TransactionScope.
///
///
/// Route context.
/// Registry name of a named instance (a leading # is stripped); null or empty for the default service.
public static RedbScope CreateRedbScope(this IRouteContext context, string? name = null)
{
ArgumentNullException.ThrowIfNull(context);
if (string.IsNullOrEmpty(name))
return CreateDefaultRedbScope(context);
var cleanName = name.TrimStart('#');
if (context.GetFromRegistry(FactoryPrefix + cleanName) is { } factory)
return OpenRedbScope(factory, $"named IRedbService '{cleanName}'");
var instance = context.GetFromRegistry(RegistryPrefix + cleanName)
?? throw new InvalidOperationException(
$"Named IRedbService '{name}' is not found in context registry. "
+ "Register it via context.RegisterRedbService(name, instance) or configure in Redb section.");
if (!instance.CanCreateScope)
throw new InvalidOperationException(
$"Named IRedbService '{cleanName}' was registered as an instance built without a DI container, so no scope "
+ "can be opened for it. Build the service through a container (services.AddRedb...) before "
+ "RegisterRedbService, or do the work on an exchange.");
return instance.CreateScope();
}
private static RedbScope CreateDefaultRedbScope(IRouteContext context)
{
// The service registered on the context first: it is what code without an exchange gets from GetRedbService().
if (context.GetService() is { } registered)
{
if (!registered.CanCreateScope)
throw new InvalidOperationException(
"The IRedbService registered on the route context was built without a DI container, so no scope can "
+ "be opened for it. Register it through a container (services.AddRedb...), or do the work on an exchange.");
return registered.CreateScope();
}
if (context.GetServiceProvider()?.GetService() is { } factory)
return OpenRedbScope(factory, "the route context's service provider");
throw new InvalidOperationException(
"IRedbService is not registered. Call services.AddRedb() / services.AddRedbPro(), "
+ "or register a named instance via context.RegisterRedbService(name, instance).");
}
private static RedbScope OpenRedbScope(IServiceScopeFactory factory, string source)
{
var scope = factory.CreateScope();
var handedOver = false;
try
{
var service = scope.ServiceProvider.GetService()
?? throw new InvalidOperationException($"The scope factory of {source} does not provide IRedbService.");
var redbScope = new RedbScope(service, scope);
handedOver = true;
return redbScope;
}
finally
{
// A failed resolution must not strand the scope it opened.
if (!handedOver)
scope.Dispose();
}
}
///
/// Resolves a PER-REQUEST scoped for a controller — its own DB
/// connection, tied to the controller's current .
///
/// Use this in controllers instead of Context.GetRedbService(): the latter resolves a
/// captive singleton (one shared, non-thread-safe connection) from the root provider, which under
/// concurrent requests surfaces as "A command is already in progress" / "Connection is busy".
///
///
public static IRedbService Redb(this RedbController controller)
{
ArgumentNullException.ThrowIfNull(controller);
return controller.Context.GetRedbService(string.Empty, controller.Exchange);
}
// ── Process with IRedbService ────────────────────────────────────
///
/// Processes the exchange with access to (async).
/// Resolves a scoped service per exchange when DI scope is available.
///
/// Route definition.
/// Async action receiving the redb service and exchange.
public static IRouteDefinition ProcessWithRedb(
this IRouteDefinition route,
Func action)
{
ArgumentNullException.ThrowIfNull(action);
return route.Process(async (exchange, ct) =>
{
var redb = ResolveRedbService(route, exchange);
await action(redb, exchange, ct).ConfigureAwait(false);
});
}
///
/// Processes the exchange with access to (sync).
/// Resolves a scoped service per exchange when DI scope is available.
///
/// Route definition.
/// Action receiving the redb service and exchange.
public static IRouteDefinition ProcessWithRedb(
this IRouteDefinition route,
Action action)
{
ArgumentNullException.ThrowIfNull(action);
return route.Process(exchange =>
{
var redb = ResolveRedbService(route, exchange);
action(redb, exchange);
});
}
// ── SetBody with IRedbService ────────────────────────────────────
///
/// Sets the exchange body using .
/// Resolves a scoped service per exchange when DI scope is available.
///
/// Route definition.
/// Factory that produces the body from service and exchange.
public static IRouteDefinition SetBodyFromRedb(
this IRouteDefinition route,
Func factory)
{
ArgumentNullException.ThrowIfNull(factory);
return route.SetBody(exchange =>
{
var redb = ResolveRedbService(route, exchange);
return factory(redb, exchange);
});
}
// ── SetHeader with IRedbService ──────────────────────────────────
///
/// Sets a header using .
/// Resolves a scoped service per exchange when DI scope is available.
///
/// Route definition.
/// Header key.
/// Factory that produces the header value from service and exchange.
public static IRouteDefinition SetHeaderFromRedb(
this IRouteDefinition route,
string headerName,
Func factory)
{
ArgumentNullException.ThrowIfNull(factory);
return route.SetHeader(headerName, exchange =>
{
var redb = ResolveRedbService(route, exchange);
return factory(redb, exchange);
});
}
// ── Named Process with IRedbService ─────────────────────────────
///
/// Processes the exchange with access to a named (async).
/// Resolves a per-exchange scoped service when a factory is registered; see
/// for scoping details.
///
/// Route definition.
/// Named redb instance (e.g. "orders-db").
/// Async action receiving the redb service and exchange.
public static IRouteDefinition ProcessWithRedb(
this IRouteDefinition route,
string name,
Func action)
{
ArgumentNullException.ThrowIfNull(action);
return route.Process(async (exchange, ct) =>
{
var redb = ResolveNamedRedbService(route, exchange, name);
await action(redb, exchange, ct).ConfigureAwait(false);
});
}
///
/// Processes the exchange with access to a named (sync).
/// Resolves a per-exchange scoped service when a factory is registered; see
/// for scoping details.
///
/// Route definition.
/// Named redb instance (e.g. "orders-db").
/// Action receiving the redb service and exchange.
public static IRouteDefinition ProcessWithRedb(
this IRouteDefinition route,
string name,
Action action)
{
ArgumentNullException.ThrowIfNull(action);
return route.Process(exchange =>
{
var redb = ResolveNamedRedbService(route, exchange, name);
action(redb, exchange);
});
}
// ── Named SetBody with IRedbService ──────────────────────────────
///
/// Sets the exchange body using a named .
/// Resolves a per-exchange scoped service when a factory is registered; see
/// for scoping details.
///
/// Route definition.
/// Named redb instance (e.g. "orders-db").
/// Factory that produces the body from service and exchange.
public static IRouteDefinition SetBodyFromRedb(
this IRouteDefinition route,
string name,
Func factory)
{
ArgumentNullException.ThrowIfNull(factory);
return route.SetBody(exchange =>
{
var redb = ResolveNamedRedbService(route, exchange, name);
return factory(redb, exchange);
});
}
// ── Named SetHeader with IRedbService ────────────────────────────
///
/// Sets a header using a named .
/// Resolves a per-exchange scoped service when a factory is registered; see
/// for scoping details.
///
/// Route definition.
/// Named redb instance (e.g. "orders-db").
/// Header key.
/// Factory that produces the header value from service and exchange.
public static IRouteDefinition SetHeaderFromRedb(
this IRouteDefinition route,
string name,
string headerName,
Func factory)
{
ArgumentNullException.ThrowIfNull(factory);
return route.SetHeader(headerName, exchange =>
{
var redb = ResolveNamedRedbService(route, exchange, name);
return factory(redb, exchange);
});
}
// ── Private helpers ──────────────────────────────────────────────
internal static IRedbService ResolveRedbService(IRouteDefinition route, IExchange exchange)
{
// Fast path: if the exchange's own DI scope already carries redb, return it WITHOUT
// resolving the route context. GetContext() walks the Parent chain, so it must not run
// when the exchange can already satisfy the request — a scopeless exchange is the only
// case that actually needs the context fallback below.
if (exchange?.ServiceProvider?.GetService() is { } scoped)
return scoped;
var context = route.GetContext()
?? throw new InvalidOperationException(
"RouteContext is not available. Ensure the route builder has been configured.");
return ResolveScopedRedb(context, exchange);
}
///
/// Resolves the default (unnamed) as a PER-EXCHANGE scoped instance
/// (its own DB connection) — never a captive singleton resolved from the root provider.
///
/// IRedbService wraps a single, non-thread-safe DB connection (EF-DbContext model). Sharing
/// one instance across concurrent exchanges/branches/requests surfaces as
/// "A command is already in progress" / "Connection is busy". This resolver guarantees isolation:
///
/// - use the exchange's own DI scope if it already carries IRedbService;
/// - otherwise create a dedicated scope from the context provider's
/// (redb is registered Scoped, so this yields a fresh
/// instance with its own connection), cached on the exchange and disposed by
/// Exchange.ReleaseScopes();
/// - only when there is NO exchange (seed/diagnostics — single-threaded bootstrap) fall back
/// to the unscoped singleton.
///
///
///
///
/// A cached on an exchange. The exchange releases every kept under
/// a __redb_scope: key when it ends, so the scope is presented as one; is the service
/// the scope was opened for.
///
private sealed class ExchangeRedbScope : IServiceScope, IAsyncDisposable
{
private readonly RedbScope _scope;
public ExchangeRedbScope(RedbScope scope) => _scope = scope;
public IRedbService Service => _scope.Service;
public IServiceProvider ServiceProvider => _scope.ServiceProvider ?? NoServices.Instance;
public void Dispose() => _scope.Dispose();
public ValueTask DisposeAsync() => _scope.DisposeAsync();
}
private sealed class NoServices : IServiceProvider
{
public static readonly NoServices Instance = new();
public object? GetService(Type serviceType) => null;
}
private static IRedbService ResolveScopedRedb(IRouteContext context, IExchange? exchange)
{
if (exchange != null)
{
// 1. Exchange's own scope already resolves redb.
if (exchange.ServiceProvider?.GetService() is { } scoped)
return scoped;
// 2. Dedicated scope cached from a previous call in this same exchange.
if (exchange.Properties.TryGetValue(DefaultScopeKey, out var cached))
{
if (cached is ExchangeRedbScope own)
return own.Service;
if (cached is IServiceScope cachedScope)
return cachedScope.ServiceProvider.GetRequiredService();
}
// 3. Create a dedicated per-exchange scope from the context provider's scope factory.
// The very fact that the unscoped singleton resolves at all proves redb is registered
// in this provider — so a fresh scope from it yields a per-exchange instance + own connection.
if (context.GetServiceProvider()?.GetService() is { } factory)
{
var scope = factory.CreateScope();
if (scope.ServiceProvider.GetService() is { } fromScope)
{
exchange.Properties[DefaultScopeKey] = scope; // disposed by Exchange.ReleaseScopes()
return fromScope;
}
scope.Dispose(); // this provider has no default redb — fall through to the registry/singleton
}
// 4. No provider scope: a service registered on the context (a host outside Tsak) opens a scope
// of the same database for this exchange when it was built through a container.
if (context.GetService() is { CanCreateScope: true } registered)
{
var redbScope = registered.CreateScope();
exchange.Properties[DefaultScopeKey] = new ExchangeRedbScope(redbScope); // disposed by Exchange.ReleaseScopes()
return redbScope.Service;
}
}
// No exchange, or no scope can be opened (a service built without a container): the unscoped singleton.
// Safe only for single-threaded seed/diagnostics.
return context.GetRedbService();
}
///
/// Resolves a named IRedbService with per-exchange scoping.
/// Uses the exchange to cache/create a scoped instance — see .
///
private static IRedbService ResolveNamedRedbService(IRouteDefinition route, IExchange exchange, string name)
{
var context = route.GetContext()
?? throw new InvalidOperationException(
"RouteContext is not available. Ensure the route builder has been configured.");
return context.GetRedbService(name, exchange);
}
}