How a .NET service sends, publishes and consumes messages with the JorgeCostaMacia.Bus family, whatever the transport. Use when writing or reviewing a command or an event record, a command handler, an event subscriber or any other consumer, sending or publishing from a handler, the retry ladder and its exclude list, the Quartz retry store, the routes and the producer, admin and consumer maps of a contracts package, the host's bus composition, or a new field in a contract. It encodes: Command/...
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Bus Dotnet?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/jorgecostamacia-bus-dotnet-code-harness)
---
name: bus-dotnet
description: >-
How a .NET service sends, publishes and consumes messages with the
JorgeCostaMacia.Bus family, whatever the transport. Use when writing or
reviewing a command or an event record, a command handler, an event
subscriber or any other consumer, sending or publishing from a handler,
the retry ladder and its exclude list, the Quartz retry store, the routes
and the producer, admin and consumer maps of a contracts package, the
host's bus composition, or a new field in a contract. It encodes:
Command/Event sealed records with their two constructors, a new field
nullable first, the contracts package versioned apart from the service,
CommandHandler<T>/EventSubscriber<T> as thin adapters, IBus Send/Publish
with the incoming transport, the standard backoff with ValidationException
excluded, retries scheduled in Quartz and run by a separate jobs worker,
and route and handler naming. The why is in `messaging`; the Kafka
specifics are in `bus-kafka-dotnet`.
---
# The bus in .NET (JorgeCostaMacia.Bus)
The .NET *how* of `messaging` (load it for the *why*), for what every transport shares. `JorgeCostaMacia.Bus` is the agnostic root. Each transport (`Bus.Kafka`, `Bus.RabbitMQ`) ships the **same simple names** in its own namespace: `Command`, `Event`, `CommandHandler<T>`, `EventSubscriber<T>`, `IBus`. To move to another transport, swap the `using`s. Everything below holds for both; the transport skill adds topics, partitions, groups and dead-letter mechanics.
**The libraries:** the contracts (`JorgeCostaMacia.Bus`) live in [bus-dotnet](https://github.com/JorgeCostaMacia/bus-dotnet). Each transport has a repository of its own: [bus-kafka-dotnet](https://github.com/JorgeCostaMacia/bus-kafka-dotnet) and [bus-rabbitmq-dotnet](https://github.com/JorgeCostaMacia/bus-rabbitmq-dotnet). `JorgeCostaMacia.Quartz`, in [quartz-dotnet](https://github.com/JorgeCostaMacia/quartz-dotnet), holds the configuration of the retry store (`WithPostgresDefaults`). How each works inside is its README's; this skill is how the code uses them.
## Message records
Messages live in the service's **contracts package**, never in the runtime. A command derives `Command`, and an event derives `Event`. Both are `sealed record`s that carry the aggregate metadata: `AggregateId`, `AggregateCorrelationId`, `AggregateOccurredAt`, `AggregateConsumers`. `AggregateConsumers` names the destinations of the message, so other subscribers can filter it out.
```csharp
public sealed record PedidosExtractCommand : Command
{
public DateTime? Date { get; init; }
public int PageSize { get; init; }
[JsonConstructor] // the transport's: the full tuple, metadata first
public PedidosExtractCommand(
Guid aggregateId,
Guid aggregateCorrelationId,
DateTime aggregateOccurredAt,
ImmutableList<string> aggregateConsumers,
DateTime? date,
int pageSize
) : base(aggregateId, aggregateCorrelationId, aggregateOccurredAt, aggregateConsumers)
{
Date = date;
PageSize = pageSize;
}
public PedidosExtractCommand( // the producers': payload first, metadata optional
DateTime? date,
int pageSize,
Guid? aggregateId = null,
Guid? aggregateCorrelationId = null,
DateTime? aggregateOccurredAt = null,
IEnumerable<string>? aggregateConsumers = null
) : base(aggregateId, aggregateCorrelationId, aggregateOccurredAt, aggregateConsumers)
{
Date = date;
PageSize = pageSize;
}
}
```
- **Keep both constructors** and keep them in step; the contracts suite (`MessageContract`) proves every message survives the wire and both constructors agree.
- Payload is primitives and other records — no value objects, no domain types: a contract is a published language, not the model.
- **A new field is nullable first.** If the JSON does not carry a constructor parameter, System.Text.Json silently gives it its default value. A non-nullable `string` then arrives as `null` and fails in the value object. So a field added in a minor is a nullable parameter, `null` by default in the convenience constructor. It becomes required only in the next major. A consumer takes it by bumping the contract's `<PackageVersion>` in `Directory.Packages.props`. Where the contracts package lives, how it is versioned apart from the service and how its major names the topics are in `messaging` and `build-dotnet`.
- Names: commands `<Module><Action>Command` (imperative), events `<Module><Fact>Event` (past tense: `Extracted`, `Loaded`).
- A `<Module>LoadedEvent` carries the row's previous state as `AggregateLoadedEvent`, of the same event type. It is `null` when the load created the row. The service builds it before it mutates the aggregate (see `messaging`).
## Handlers and subscribers
```csharp
internal sealed class PedidosExtractCommandHandler : CommandHandler<PedidosExtractCommand>
{
public override async Task Handle(
CommandContext<PedidosExtractCommand> context,
CancellationToken cancellationToken = default)
{
List<Command> commands = await _extractService.Extract(
context.Message.Date,
context.Message.PageSize,
context.Message.AggregateCorrelationId,
context.Message.AggregateConsumers,
cancellationToken);
await _bus.Send(commands, context.Transport, cancellationToken);
// the success line — see logging-dotnet
}
}
```
- `internal sealed`, in `Presentation/Bus/`, constructor-injected with its use-case service(s), `IBus` and `ILogger<T>`.
- **Thin**: unpack `context.Message` into the service's own parameters; never pass the message into Application. Call the service with the **live token**. Then `Send` / `Publish` what it returned, and log. No rule, no try/catch, no retry: a failure propagates to the bus.
- **Send and publish with `context.Transport`** — it carries the incoming envelope, so what the handler causes inherits its correlation.
- An event subscriber has the same shape (`EventSubscriber<T>`, `EventContext<T>`). Its name tells what it does and what it listens to: `<Module><Action>On<Source><Module><Event>EventSubscriber`.
## Retries
Register every handler and subscriber with the **same ladder and the same exclude list**:
```csharp
ImmutableList<TimeSpan> retry = ImmutableList.Create(
TimeSpan.FromMinutes(5),
TimeSpan.FromMinutes(15),
TimeSpan.FromMinutes(30),
TimeSpan.FromHours(1),
TimeSpan.FromHours(12),
TimeSpan.FromDays(1));
ImmutableList<Type> exclude = ImmutableList.Create(typeof(ValidationException));
```
- **`ValidationException` (the shared base, `JorgeCostaMacia.DDD.Exception`'s) is always excluded**: the bus parks a malformed message at once and never retries it. A validator must override `RaiseValidationException` to throw it (see `validation-dotnet`); FluentValidation's own exception is not that base and climbs the ladder. A concurrency failure is *not* excluded — the retry re-decides against the current state. A consumer whose write is not idempotent also excludes the `ExistException` a retry cannot change (see `messaging`).
- A step of `TimeSpan.Zero` requeues at once; a positive one is **scheduled** through the retry store.
- **The retry store is Quartz**: `AddQuartz(q => q.WithPostgresDefaults(<scheduler>, <connection name>, <table prefix>))` plus `AddRetryContext()` from `JorgeCostaMacia.Bus.<Transport>.Retry.Quartz`. `WithPostgresDefaults` comes from `JorgeCostaMacia.Quartz`. Every service that schedules retries shares one scheduler name and one store. A service **only schedules** retries: it never adds `AddQuartzHostedService`. A **separate jobs worker**, on the same scheduler and store, starts the scheduler and fires the retries. So a deploy of a service never changes who runs the retries. Without a retry store, the bus cannot schedule a delayed retry and parks the message as terminal.
## Routes and the maps
- **Declare the routes once, in the contracts package**, as `static readonly string`s: a base per module, then its events and its commands. The public `<Module>Context` re-exposes them as `Bus<Module><Message>Route`. The runtime derives its own: a handler is `{command route}.handler`, a subscriber `{base handler route}.on.{source event route}.subscriber`. A route with no message behind it (a `load.command` that only anchors subscribers) is kept: removing it renames the subscribers' routes.
- **Three maps, composed in the host's `AddBusContext(configuration, producer, consumer, admin)`**:
- **producer** and **admin** — the service's own contracts maps **first**, then those of every service it consumes;
- **consumer** — the service's own runtime modules (`Map<Module>BusContext`), which register its handlers and subscribers with their routes, ladder and exclude list.
- The host's **composition test** builds all of it with fake settings (see `testing-dotnet`).
## Logging
Handlers log one success line each; the bus pipeline logs failures, retries and parking. What each line carries (the payload, the masked secrets, the message `Body` that the transports push) is in `logging-dotnet`, under *Bus hosts*.