Path: redb-route/redb.Route/Core/ProducerTemplate.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/ProducerTemplate.cs
----
using System.Diagnostics;
using System.Collections.Concurrent;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
namespace redb.Route.Core;
///
/// Default implementation of .
/// Provides a client API for sending messages to endpoints outside of route pipelines.
/// Must be started via before use.
/// Thread-safe: all public methods check started state, endpoint resolution is delegated
/// to which uses concurrent collections.
/// Caches producers per endpoint for performance (avoids CreateProducer on every call).
///
public class ProducerTemplate : IProducerTemplate, IDisposable, IAsyncDisposable
{
private readonly ConcurrentDictionary _producerCache = new(StringComparer.OrdinalIgnoreCase);
private volatile bool _started;
private volatile bool _disposed;
// Captured once at construction; null when context has no DI provider (e.g. unit-test routes).
// When non-null, every Exchange we create owns a fresh DI scope so per-request scoped
// services (IRedbService and its NpgsqlConnection, OpenIddict stores, ...) are isolated
// between concurrent ProducerTemplate calls. Each Send/RequestBody method below MUST
// dispose the exchange in finally so the scope (and connection) is released promptly.
private readonly IServiceScopeFactory? _scopeFactory;
///
/// Initializes a new instance with the specified route context.
///
/// The route context for endpoint resolution.
/// Thrown when is null.
public ProducerTemplate(IRouteContext context)
{
Context = context ?? throw new ArgumentNullException(nameof(context));
_scopeFactory = context.GetServiceProvider()?.GetService();
}
///
public IRouteContext Context { get; }
///
public bool IsStarted => _started;
// ── Synchronous Send ──
///
public void Send(string endpointUri, object body)
{
EnsureStarted();
var endpoint = Context.GetEndpoint(endpointUri);
Send(endpoint, body);
}
///
public void Send(IEndpoint endpoint, object body)
{
EnsureStarted();
var exchange = CreateExchange(body);
try { Send(endpoint, exchange); }
finally { exchange.DisposeAsync().AsTask().GetAwaiter().GetResult(); }
}
///
public void Send(IEndpoint endpoint, IExchange exchange)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(exchange);
var producer = GetOrCreateProducer(endpoint);
ProcessCounted(endpoint, producer, exchange).GetAwaiter().GetResult();
}
///
public void Send(string endpointUri, IExchange exchange)
{
EnsureStarted();
var endpoint = Context.GetEndpoint(endpointUri);
Send(endpoint, exchange);
}
///
public void Send(IEndpoint endpoint, IMessage message)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(message);
var exchange = Exchange.Create(message, _scopeFactory);
try { Send(endpoint, exchange); }
finally { exchange.DisposeAsync().AsTask().GetAwaiter().GetResult(); }
}
///
public void Send(string endpointUri, IMessage message)
{
EnsureStarted();
var endpoint = Context.GetEndpoint(endpointUri);
Send(endpoint, message);
}
///
public void Send(IEndpoint endpoint, IProcessor processor)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(processor);
var exchange = CreateExchange(null);
try
{
processor.Process(exchange).GetAwaiter().GetResult();
var producer = GetOrCreateProducer(endpoint);
ProcessCounted(endpoint, producer, exchange).GetAwaiter().GetResult();
}
finally { exchange.DisposeAsync().AsTask().GetAwaiter().GetResult(); }
}
// ── Async Send ──
///
public async Task SendAsync(IEndpoint endpoint, object body)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(endpoint);
var exchange = CreateExchange(body);
try
{
var producer = GetOrCreateProducer(endpoint);
// ConnectableProducer-based transports demand Start() before Process();
// idempotent — the started flag short-circuits subsequent calls.
await producer.Start().ConfigureAwait(false);
await ProcessCounted(endpoint, producer, exchange).ConfigureAwait(false);
}
finally { await exchange.DisposeAsync().ConfigureAwait(false); }
}
///
public async Task SendAsync(string endpointUri, object body)
{
EnsureStarted();
var endpoint = Context.GetEndpoint(endpointUri);
await SendAsync(endpoint, body).ConfigureAwait(false);
}
///
public async Task SendAsync(IEndpoint endpoint, IMessage message)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(message);
var exchange = Exchange.Create(message, _scopeFactory);
try
{
var producer = GetOrCreateProducer(endpoint);
// ConnectableProducer-based transports (http, kafka, amqp, …)
// demand Start() before Process(); idempotent — second Start is
// a no-op on the started flag.
await producer.Start().ConfigureAwait(false);
await ProcessCounted(endpoint, producer, exchange).ConfigureAwait(false);
}
finally { await exchange.DisposeAsync().ConfigureAwait(false); }
}
///
public async Task SendAsync(string endpointUri, IMessage message)
{
EnsureStarted();
var endpoint = Context.GetEndpoint(endpointUri);
await SendAsync(endpoint, message).ConfigureAwait(false);
}
// ── Async Send / Request of a pre-built exchange (caller-owned) ──
///
public async Task SendAsync(IEndpoint endpoint, IExchange exchange, CancellationToken cancellationToken = default)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(exchange);
// Caller-owned exchange: unlike the body/message overloads we do NOT create, clone or
// dispose it, and we attach no DI scope — whatever scope the exchange carries (or lacks)
// is the caller's responsibility. A snapshot cloned from a completed exchange may reference
// a disposed scope; the caller must give it a live scope before replay if it needs one.
var producer = GetOrCreateProducer(endpoint);
await producer.Start(cancellationToken).ConfigureAwait(false);
await ProcessCounted(endpoint, producer, exchange, cancellationToken).ConfigureAwait(false);
}
///
public async Task SendAsync(string endpointUri, IExchange exchange, CancellationToken cancellationToken = default)
{
EnsureStarted();
var endpoint = Context.GetEndpoint(endpointUri);
await SendAsync(endpoint, exchange, cancellationToken).ConfigureAwait(false);
}
///
public async Task RequestAsync(IEndpoint endpoint, IExchange exchange, CancellationToken cancellationToken = default)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(exchange);
// Caller-owned (see SendAsync(IExchange) above): not cloned or disposed here.
exchange.Pattern = ExchangePattern.InOut;
var producer = GetOrCreateProducer(endpoint);
await producer.Start(cancellationToken).ConfigureAwait(false);
await ProcessCounted(endpoint, producer, exchange, cancellationToken).ConfigureAwait(false);
return exchange;
}
///
public async Task RequestAsync(string endpointUri, IExchange exchange, CancellationToken cancellationToken = default)
{
EnsureStarted();
var endpoint = Context.GetEndpoint(endpointUri);
return await RequestAsync(endpoint, exchange, cancellationToken).ConfigureAwait(false);
}
// ── Request/Reply ──
///
public async Task