Path: redb-route/redb.Route/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
#pragma warning disable CS0619
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Configuration;
using redb.Route.Core;
namespace redb.Route.Extensions;
///
/// Extension methods for registering redb.Route in a Microsoft.Extensions.DependencyInjection container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the route context, hosted service, and route builders.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.AddRouteBuilder<MyRoutes>();
/// route.AddComponent(new RedisComponent());
/// });
///
///
///
/// Service collection.
/// Optional configuration action.
/// The service collection for chaining.
public static IServiceCollection AddRedbRoute(
this IServiceCollection services,
Action? configure = null)
{
ArgumentNullException.ThrowIfNull(services);
// Register context as singleton — one context per host
services.TryAddSingleton(sp =>
{
var loggerFactory = sp.GetService();
var options = sp.GetService>()?.Value;
return new RouteContext(loggerFactory: loggerFactory, options: options);
});
// Shared registry for cross-context direct-vm / vm components
services.TryAddSingleton();
// Register IRouteContext as the same singleton
services.TryAddSingleton(sp => sp.GetRequiredService());
// Register the hosted service
services.AddHostedService();
// Apply user configuration
if (configure != null)
{
var builder = new RedbRouteBuilder(services);
configure(builder);
}
return services;
}
///
/// Registers a component as a singleton and hooks it into the route context through
/// — the hook
/// applies at startup. This is THE registration primitive for connector packages
/// (AddRedbRouteKafka() and friends): a lazy marker singleton that nobody
/// resolves never reaches the context.
///
/// Concrete component type.
public static IServiceCollection AddRouteComponent(this IServiceCollection services)
where TComponent : class, IComponent
{
services.TryAddSingleton();
services.AddSingleton(sp =>
new ComponentConfigurator(sp));
return services;
}
///
/// Registers an arbitrary startup callback as an .
/// For connectors whose registration is more than a bare AddComponent — wiring a
/// shared server manager, several components, named registry entries.
///
public static IServiceCollection AddRouteContextConfigurator(
this IServiceCollection services,
Action configure)
{
ArgumentNullException.ThrowIfNull(configure);
services.AddSingleton(sp =>
new DelegateContextConfigurator(sp, configure));
return services;
}
}
/// Applies a delegate against the context at startup (see ).
internal sealed class DelegateContextConfigurator : IRouteContextConfigurator
{
private readonly IServiceProvider _sp;
private readonly Action _configure;
public DelegateContextConfigurator(IServiceProvider sp, Action configure)
{
_sp = sp;
_configure = configure;
}
public void Configure(RouteContext context) => _configure(_sp, context);
}
///
/// Fluent builder for configuring route context registration within DI.
///
public sealed class RedbRouteBuilder
{
private readonly IServiceCollection _services;
/// Creates a new builder.
internal RedbRouteBuilder(IServiceCollection services)
{
_services = services;
}
/// Gets the underlying service collection for advanced scenarios.
public IServiceCollection Services => _services;
///
/// Registers a implementation.
/// Instances are resolved from DI, so constructor injection works.
///
/// Concrete route builder type.
/// This builder for chaining.
/// was already added by .
public RedbRouteBuilder AddRouteBuilder() where TBuilder : RouteBuilder
{
if (IsDiscovered(typeof(TBuilder)))
throw new InvalidOperationException(
$"Route builder '{typeof(TBuilder).FullName}' was already added by AddRouteBuilders. " +
"Leave it out of the discovery with the filter, or do not add it again.");
// Register the CONCRETE type (the configurator resolves TBuilder) and expose the SAME singleton as the
// base RouteBuilder for enumeration. Registering only the base left GetRequiredService()
// unresolvable, so host startup threw "No service for type '…' has been registered".
_services.AddSingleton();
_services.AddSingleton(sp => sp.GetRequiredService());
// Hook up to context via a post-configure callback
_services.AddSingleton(sp =>
new RouteBuilderConfigurator(sp));
return this;
}
///
/// Registers every route builder of — each public, non-abstract, closed class
/// deriving from — as does, so constructor
/// injection works (Apache Camel's routes discovery).
///
/// Assemblies to scan; at least one.
/// This builder for chaining.
///
/// A builder type is already registered, or an assembly's types cannot all be loaded. Nothing is registered then.
///
public RedbRouteBuilder AddRouteBuilders(params Assembly[] assemblies)
=> AddDiscoveredRouteBuilders(assemblies, filter: null);
///
/// with a filter choosing which builders to take — the place for a
/// condition (environment, configuration) and for leaving a builder out.
///
/// Assemblies to scan; at least one.
/// Returns true for a builder type to register.
/// This builder for chaining.
/// As .
public RedbRouteBuilder AddRouteBuilders(IEnumerable assemblies, Func filter)
{
ArgumentNullException.ThrowIfNull(filter);
return AddDiscoveredRouteBuilders(assemblies, filter);
}
private RedbRouteBuilder AddDiscoveredRouteBuilders(IEnumerable assemblies, Func? filter)
{
var types = RouteBuilderDiscovery.FindBuilderTypes(assemblies, filter);
// A type already registered would add its routes twice and fail only at host start with a duplicate route
// id; said now, with the type's name. Checked for all before any is registered.
foreach (var type in types)
{
if (_services.Any(d => d.ServiceType == type) || IsDiscovered(type))
throw new InvalidOperationException(
$"Route builder '{type.FullName}' is already registered. " +
"Leave it out of the discovery with the filter, or do not register it explicitly.");
}
foreach (var type in types)
{
// The AddRouteBuilder shape: the concrete type, the same singleton as RouteBuilder, a configurator
// that adds it to the context — the container builds it, so its constructor may take services.
_services.AddSingleton(type);
_services.AddSingleton(sp => (RouteBuilder)sp.GetRequiredService(type));
_services.AddSingleton(sp => new DiscoveredRouteBuilderConfigurator(sp, type));
_services.AddSingleton(new DiscoveredRouteBuilder(type));
}
return this;
}
private bool IsDiscovered(Type builderType)
=> _services.Any(d => d.ImplementationInstance is DiscoveredRouteBuilder discovered && discovered.BuilderType == builderType);
///
/// Registers a component for a custom URI scheme.
///
/// Concrete component type.
/// This builder for chaining.
public RedbRouteBuilder AddComponent() where TComponent : class, IComponent
{
// Same fix as AddRouteBuilder: the ComponentConfigurator resolves the concrete TComponent, so register
// it directly and expose the same singleton as IComponent for enumeration.
_services.AddSingleton();
_services.AddSingleton(sp => sp.GetRequiredService());
_services.AddSingleton(sp =>
new ComponentConfigurator(sp));
return this;
}
///
/// Registers an inline route builder using an action.
///
/// Action to define routes inline.
/// This builder for chaining.
public RedbRouteBuilder AddRoutes(Action configure)
{
ArgumentNullException.ThrowIfNull(configure);
_services.AddSingleton(
_ => new InlineRouteConfigurator(configure));
return this;
}
}
///
/// Contract for context configuration callbacks applied before start.
/// Implementations are resolved from DI and applied by .
///
public interface IRouteContextConfigurator
{
/// Applies configuration to the context.
void Configure(RouteContext context);
}
internal sealed class RouteBuilderConfigurator : IRouteContextConfigurator
where TBuilder : RouteBuilder
{
private readonly IServiceProvider _sp;
public RouteBuilderConfigurator(IServiceProvider sp) => _sp = sp;
public void Configure(RouteContext context)
{
var builder = _sp.GetRequiredService();
context.AddRoutes(builder);
}
}
/// Adds a route builder registered by to the context.
internal sealed class DiscoveredRouteBuilderConfigurator : IRouteContextConfigurator
{
private readonly IServiceProvider _sp;
private readonly Type _builderType;
public DiscoveredRouteBuilderConfigurator(IServiceProvider sp, Type builderType)
{
_sp = sp;
_builderType = builderType;
}
public void Configure(RouteContext context)
=> context.AddRoutes((RouteBuilder)_sp.GetRequiredService(_builderType));
}
/// Marks a route builder type registered by assembly discovery, so a second registration of it is refused.
internal sealed record DiscoveredRouteBuilder(Type BuilderType);
internal sealed class ComponentConfigurator : IRouteContextConfigurator
where TComponent : class, IComponent
{
private readonly IServiceProvider _sp;
public ComponentConfigurator(IServiceProvider sp) => _sp = sp;
public void Configure(RouteContext context)
{
var component = _sp.GetRequiredService();
context.AddComponent(component);
}
}
internal sealed class InlineRouteConfigurator : IRouteContextConfigurator
{
private readonly Action _configure;
public InlineRouteConfigurator(Action configure)
=> _configure = configure;
public void Configure(RouteContext context) => context.AddRoutes(_configure);
}