Chatter.MessageBrokers.SqlServiceBroker
0.16.0
See the version list below for details.
dotnet add package Chatter.MessageBrokers.SqlServiceBroker --version 0.16.0
NuGet\Install-Package Chatter.MessageBrokers.SqlServiceBroker -Version 0.16.0
<PackageReference Include="Chatter.MessageBrokers.SqlServiceBroker" Version="0.16.0" />
<PackageVersion Include="Chatter.MessageBrokers.SqlServiceBroker" Version="0.16.0" />
<PackageReference Include="Chatter.MessageBrokers.SqlServiceBroker" />
paket add Chatter.MessageBrokers.SqlServiceBroker --version 0.16.0
#r "nuget: Chatter.MessageBrokers.SqlServiceBroker, 0.16.0"
#:package Chatter.MessageBrokers.SqlServiceBroker@0.16.0
#addin nuget:?package=Chatter.MessageBrokers.SqlServiceBroker&version=0.16.0
#tool nuget:?package=Chatter.MessageBrokers.SqlServiceBroker&version=0.16.0
<a name="chatter-sqlservicebroker"></a> Chatter.MessageBrokers.SqlServiceBroker
A SQL Server Service Broker transport for Chatter.MessageBrokers — send and receive brokered messages over SQL Service Broker dialogs.
Overview
Chatter.MessageBrokers.SqlServiceBroker is a concrete, SQL Server Service Broker implementation of the technology-agnostic interfaces defined by Chatter.MessageBrokers (itself built on Chatter.CQRS).
Where the core library defines IMessagingInfrastructureReceiver, IMessagingInfrastructureDispatcher, and the recovery abstractions (retry, circuit breaker), this package supplies the SQL Service Broker realizations:
SqlServiceBrokerReceiverdequeues messages withWAITFOR (RECEIVE ...).SqlServiceBrokerSenderenqueues messages by opening a dialog (BEGIN DIALOG),SEND ON CONVERSATION, and (optionally)END CONVERSATION.SqlCircuitBreakerExceptionPredicatesProviderandSqlRetryExceptionPredicatesProviderteach the core recovery pipeline which SQL exceptions are transient and which are terminal.
It registers itself with Chatter through an IChatterBuilder extension, AddSqlServiceBroker(...), chained off AddMessageBrokers(...) — the same way the sibling Chatter.MessageBrokers.AzureServiceBus package adds AddAzureServiceBus(...).
Installation
dotnet add package Chatter.MessageBrokers.SqlServiceBroker
Getting Started
Register Chatter CQRS, add message brokers, then add the SQL Service Broker infrastructure with a connection string. The DI entry point is AddSqlServiceBroker (in the Microsoft.Extensions.DependencyInjection namespace), configured via the SqlServiceBrokerOptionsBuilder.
using Microsoft.Extensions.DependencyInjection;
services.AddChatterCqrs(Configuration, builder =>
{
builder
.AddMessageBrokers()
.AddSqlServiceBroker(ssb =>
{
ssb.AddSqlServiceBrokerOptions(
Configuration.GetValue<string>("ConnectionStrings:MyDatabase"))
// register a receiver for a message type bound to a Service Broker queue
.AddQueueReceiver<MyIntegrationEvent>("Chatter_Queue_MyIntegrationEvent");
});
});
AddQueueReceiver<TMessage> binds a Chatter.CQRS.IMessage type to a Service Broker queue (the queue name is used as both the receive path and the message description). Optional parameters let you set an error/dead-letter service path, transaction mode, and maxReceiveAttempts (default 10):
ssb.AddQueueReceiver<MyIntegrationEvent>(
queueName: "Chatter_Queue_MyIntegrationEvent",
errorQueuePath: "Chatter_Service_DeadLetter",
transactionMode: TransactionMode.FullAtomicityViaInfrastructure,
deadLetterServicePath: "Chatter_Service_DeadLetter",
maxReceiveAttempts: 8);
Sending / publishing
Within a message handler, dispatch out through the broker using the standard Chatter context, or via the SQL Service Broker-specific dispatcher extension:
using Chatter.CQRS.Context;
public class MyHandler : IMessageHandler<SomeCommand>
{
public Task Handle(SomeCommand message, IMessageHandlerContext context)
{
// SqlServiceBroker() returns an ISqlServiceBrokerContextDispatcher
return context.SqlServiceBroker()
.Send(new AnotherCommand(), "Chatter_Service_AnotherCommand");
}
}
The context.SqlServiceBroker() extension returns an ISqlServiceBrokerContextDispatcher, which exposes Send, Publish, and Forward and pins the outbound message to the SQL Service Broker infrastructure. The destinationPath is the target Service Broker service the sender opens a dialog TO.
Configuration
Options are modeled by SqlServiceBrokerOptions and assembled with SqlServiceBrokerOptionsBuilder. Configure them either by passing values to AddSqlServiceBrokerOptions(...) or by using the fluent With.../Use... methods.
| Property | Builder method | Default | Purpose |
|---|---|---|---|
ConnectionString |
AddSqlServiceBrokerOptions(connectionString) / WithConnectionString(...) |
(required) | SQL Server connection string used for all Service Broker communication. |
MessageBodyType |
WithMessageBodyType(...) / WithJsonBodyType() |
application/json; charset=utf-16 |
Content type used to encode/decode the message body. |
ReceiverTimeoutInMilliseconds |
WithReceiverTimeout(...) |
-1 (wait indefinitely) |
Timeout passed to WAITFOR (RECEIVE ...). -1 waits forever; an elapsed timeout yields an empty result. |
ConversationLifetimeInSeconds |
WithConversationLifetime(...) |
0 (no LIFETIME) |
Maximum time a dialog stays open (BEGIN DIALOG ... WITH LIFETIME). |
ConversationEncryption |
UseConversationEncryption() |
false |
Whether dialog messages are encrypted when leaving the SQL Server instance. |
CompressMessageBody |
WithMessageBodyCompression() |
true |
Gzip the body on send via T-SQL compress(...); the receiver auto-decompresses when it detects the 0x1F8B gzip header. |
CleanupOnEndConversation |
WithConversationCleanup() |
false |
Issue END CONVERSATION ... WITH CLEANUP to forcibly drop conversations that cannot complete normally. |
EndConversationAfterDispatch |
EndConversationAfterDispatch(bool) |
true |
When true, the sender ends the dialog after each dispatch (emits an EndDialog message). |
SqlServiceBrokerOptionsBuilder.Build() throws if no options were configured, if the connection string is null/whitespace, or if the message body type is missing.
Recovery (retry and circuit breaker) is supplied automatically: AddSqlServiceBroker registers SqlRetryExceptionPredicatesProvider and SqlCircuitBreakerExceptionPredicatesProvider, which classify SQL failures as transient (SqlException.IsTransient and the package's own list of known transient error numbers) so the core Chatter recovery pipeline retries or trips the breaker appropriately.
Errors 208 "invalid object name" and 102 "incorrect syntax" are terminal, not transient: both the retry and circuit-breaker exception predicate providers exclude those numbers, and the receiver surfaces them as a CriticalReceiverException naming the configured queue — a host started before its queue exists stops instead of retrying forever. See ADR-0037.
SQL Setup
This package is a transport over existing SQL Service Broker objects — it does not provision them. At runtime it only emits Service Broker DML against the objects you have already created:
Scripts/ command |
T-SQL emitted | When |
|---|---|---|
BeginDialogConversationCommand |
BEGIN DIALOG ... FROM SERVICE ... TO SERVICE ... [ON CONTRACT ...] WITH ENCRYPTION = ON\|OFF [, LIFETIME ...] |
Sender, per outbound message. |
SendOnConversationCommand |
SEND ON CONVERSATION @handle [MESSAGE TYPE ...] (@body) (wrapped in compress(...) when compression is on) |
Sender, after the dialog opens. |
EndDialogConversationCommand |
END CONVERSATION @handle [WITH ERROR ... DESCRIPTION ...] [WITH CLEANUP] |
Sender (when EndConversationAfterDispatch), and receiver on ack/deadletter/EndDialog and on every discard of a received message. |
ReceiveMessageFromQueueCommand |
WAITFOR (RECEIVE TOP(1) ... FROM <queue>) [, TIMEOUT ...] |
Receiver, to dequeue. |
Note: the queue name is bracket-quoted into the emitted
RECEIVEstatement rather than interpolated raw. A dotted name (e.g.dbo.MyQueue) is read asschema.queueand each part is quoted separately ([dbo].[MyQueue]). A one-part queue name that legitimately contains a dot must be pre-bracketed in configuration —[my.queue]— which is then passed through unsplit instead of being split on the dot. An already-bracketed queue name ([MyQueue]or[dbo].[MyQueue]) is accepted verbatim, so existing pre-bracketed configuration keeps working unchanged. A configured name that resolves to an empty part (e.g.dbo.or.MyQueue) throws anArgumentExceptionwhen the command is built, instead of reaching the server as written.
You are responsible for provisioning the Service Broker schema manually (or via your own migration tooling) before using this package. At minimum you need:
ALTER DATABASE [Db] SET ENABLE_BROKER;on the target database.- A message type and contract — the library tags Chatter-originated messages with message type
//Chatter/BrokeredMessageand service contract//Chatter(seeServicesMessageTypes). It also accepts the built-inDEFAULTmessage type. - The queues you reference in
AddQueueReceiver<T>(queueName, ...)(the receive path) and any dead-letter queue/service path you configure. - The services you send to (the
destinationPath/ target service supplied when sending).
On receive, the library filters by message type: only //Chatter/BrokeredMessage and DEFAULT are surfaced to handlers; http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog messages are acknowledged and ended, and every other type is discarded. A discarded message — a Service Broker Error, a message of a type this package does not accept, or an accepted type with a null body — has its conversation ended as part of settling it: on the RECEIVE's own transaction under a transactional mode, so the two commit together; under TransactionMode.None there is no receive transaction, so the RECEIVE has already autocommitted and the END CONVERSATION follows it as a separate autocommit, and a process that dies between the two can leave that one endpoint open. http://schemas.microsoft.com/SQL/ServiceBroker/Error messages are additionally logged at Error, with the Service Broker error code and description projected as their own structured log fields. The code is parsed as a 32-bit integer from the error body and logged as that integer re-rendered — never as peer text. Only printable letters, marks, numbers, punctuation, symbols and spaces are logged from the description, anything else becomes a space, and it is capped at 3000 characters. A missing body logs the <no error payload> placeholder for both fields; a body that is not valid UTF-16, whose code does not parse as a 32-bit integer, or that cannot otherwise be read logs the <unreadable error payload> placeholder for both fields instead. See ADR-0037. The receiver also handles dialog lifecycle (ack = END CONVERSATION, nack = transaction rollback, deadletter = resend to the configured dead-letter service path).
Note: automatic provisioning of Service Broker objects (queues, services, contracts, message types,
ENABLE_BROKER) lives in the separateChatter.SqlChangeFeedpackage, not here.
Header Propagation (including Trace Context)
Only the Chatter envelope message type round-trips the Message Context. Two receive paths deliberately build a fresh, empty header dictionary, so every upstream header is dropped:
- The
DEFAULTmessage type receive path. ADEFAULT-typed message carries a raw body with no Chatter envelope, so there is no context to restore; the receiver hands the handler a fresh dictionary. Context survives only when the sending application supplies the//Chatter/BrokeredMessagemessage type, whose deserialized envelope carries its ownMessageContext. - The deadletter path, which likewise constructs a fresh dictionary for the dead-lettered message.
This is a pre-existing limitation that affects all headers alike — correlation id, group id, application headers, and (since ADR-0010) the W3C trace-context headers traceparent / tracestate. It is not something Chatter's opt-in tracing introduced, and closing it is a change to these receive paths rather than to the instrumentation.
The consequence for tracing: a distributed trace continues across this transport on the Chatter envelope path, and starts a new trace on the DEFAULT path. Both behaviors are pinned by conformance tests, so a change that accidentally fixes or worsens either is visible.
Domain Language
See the domain glossary for definitions of Service Broker Receiver, Service Broker Sender, Queue, Conversation, Setup Scripts, and Service Broker Options.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Chatter.MessageBrokers (>= 0.35.0)
- Microsoft.Data.SqlClient (>= 7.0.1)
- Microsoft.Extensions.Hosting (>= 10.0.0)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on Chatter.MessageBrokers.SqlServiceBroker:
| Package | Downloads |
|---|---|
|
Chatter.SqlTableWatcher
A library that leverags SQL Service Broker to trigger Chatter events when table state changes. |
|
|
Chatter.SqlChangeFeed
A library that leverags SQL Service Broker to send sql table changes (insert, update, delete) to a change feed queue for further processing by .NET code. |
|
|
Chatter.IntegrationEventRelay.ServiceBroker
SQL Service Broker change source for Chatter.IntegrationEventRelay: captures row changes with triggers and Chatter.SqlChangeFeed |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.18.1 | 172 | 10/17/2026 |
| 0.18.0 | 406 | 9/29/2026 |
| 0.17.0 | 414 | 9/29/2026 |
| 0.16.1 | 126 | 9/24/2026 |
| 0.16.0 | 123 | 9/24/2026 |
| 0.15.0 | 113 | 9/24/2026 |
| 0.14.5 | 126 | 9/23/2026 |
| 0.14.4 | 138 | 9/15/2026 |
| 0.14.3 | 128 | 9/13/2026 |
| 0.14.1 | 157 | 9/2/2026 |
| 0.14.0 | 189 | 9/1/2026 |
| 0.13.0 | 128 | 8/31/2026 |
| 0.12.2 | 216 | 6/16/2026 |
| 0.8.1 | 176 | 6/16/2026 |
| 0.8.0 | 172 | 5/30/2026 |
| 0.7.5 | 1,092 | 9/20/2022 |
| 0.7.4 | 1,324 | 4/2/2022 |
| 0.7.3 | 911 | 4/1/2022 |
| 0.7.2 | 1,768 | 3/4/2022 |