Path: redb-route/redb.Route/Components/SharedVmRegistry.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/Components/SharedVmRegistry.cs
----
using System.Collections.Concurrent;
using System.Threading.Channels;
using redb.Route.Abstractions;
namespace redb.Route.Components;
///
/// Shared cross-context registry for direct-vm and vm components.
/// Registered as a singleton in DI — all RouteContexts share the same instance,
/// enabling cross-context communication without static state.
///
public class SharedVmRegistry
{
// ── direct-vm: synchronous cross-context processors ──
private readonly ConcurrentDictionary _processors = new(StringComparer.OrdinalIgnoreCase);
/// Registers a processor for a direct-vm endpoint name.
/// true if registered; false if another consumer already holds this name.
public bool TryRegisterProcessor(string name, IProcessor processor)
{
ArgumentNullException.ThrowIfNull(name);
ArgumentNullException.ThrowIfNull(processor);
return _processors.TryAdd(name, processor);
}
/// Unregisters the processor for a direct-vm endpoint name (only if same instance).
public bool TryUnregisterProcessor(string name, IProcessor processor)
{
ArgumentNullException.ThrowIfNull(name);
ArgumentNullException.ThrowIfNull(processor);
return _processors.TryRemove(new KeyValuePair(name, processor));
}
/// Gets the processor for a direct-vm endpoint name, or null if none registered.
public IProcessor? GetProcessor(string name)
{
return _processors.TryGetValue(name, out var p) ? p : null;
}
// ── vm: asynchronous cross-context channels ──
private readonly ConcurrentDictionary> _channels = new(StringComparer.OrdinalIgnoreCase);
/// Gets or creates the shared channel for a vm endpoint name.
public Channel GetOrCreateChannel(string name, int boundedSize = 0)
{
ArgumentNullException.ThrowIfNull(name);
return _channels.GetOrAdd(name, _ => boundedSize > 0
? Channel.CreateBounded(new BoundedChannelOptions(boundedSize)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false
})
: Channel.CreateUnbounded(new UnboundedChannelOptions
{
SingleReader = false,
SingleWriter = false
}));
}
/// Tries to remove a channel (e.g. on last consumer stop). Returns the removed channel if any.
public bool TryRemoveChannel(string name, out Channel? channel)
{
var result = _channels.TryRemove(name, out var ch);
channel = ch;
return result;
}
}