MessageWeaver.AzureServiceBus
0.1.0-alpha.2
See the version list below for details.
dotnet add package MessageWeaver.AzureServiceBus --version 0.1.0-alpha.2
NuGet\Install-Package MessageWeaver.AzureServiceBus -Version 0.1.0-alpha.2
<PackageReference Include="MessageWeaver.AzureServiceBus" Version="0.1.0-alpha.2" />
<PackageVersion Include="MessageWeaver.AzureServiceBus" Version="0.1.0-alpha.2" />
<PackageReference Include="MessageWeaver.AzureServiceBus" />
paket add MessageWeaver.AzureServiceBus --version 0.1.0-alpha.2
#r "nuget: MessageWeaver.AzureServiceBus, 0.1.0-alpha.2"
#:package MessageWeaver.AzureServiceBus@0.1.0-alpha.2
#addin nuget:?package=MessageWeaver.AzureServiceBus&version=0.1.0-alpha.2&prerelease
#tool nuget:?package=MessageWeaver.AzureServiceBus&version=0.1.0-alpha.2&prerelease
MessageWeaver
A .NET messaging library for Azure Service Bus that uses source generators to eliminate boilerplate and provide compile-time safety for message routing, handler discovery, and dependency injection registration.
Why MessageWeaver?
Working with Azure Service Bus directly means writing repetitive code for handler registration, message routing, serialization, retry policies, and infrastructure provisioning. MessageWeaver handles all of this through a combination of attributes and Roslyn source generators:
- Declare your intent with attributes — annotate messages with
[Message]and handlers with[QueueHandler]or[SubscriptionHandler] - Source generators do the wiring — handler factories, DI registration, and destination routing are generated at compile time with zero reflection
- Built-in resilience — configurable retry policies with exponential backoff, jitter, and multi-namespace failover powered by Polly
- Automatic infrastructure — queues, topics, and subscriptions are created on-the-fly when they don't exist
Product goals
- Simple by default — make messaging straightforward for common scenarios with minimal configuration.
- POCO-first messaging — handle serialization and deserialization of plain C# objects without framework-heavy models.
- Excellent observability — provide strong traceability, logging, and diagnostics for local development and distributed cloud systems.
- Practical reliability — include sensible reliability features that are easy to understand and operate.
- Great developer experience — optimize for clear APIs, fast setup, and compile-time feedback.
- Extensible architecture — keep extension points open for advanced and domain-specific use cases.
Packages
| Package | Description |
|---|---|
MessageWeaver.Abstractions |
Core interfaces, attributes, and contracts (IMessage, IMessageHandler<T>, IMessagePublisher) |
MessageWeaver.AzureServiceBus |
Azure Service Bus publisher and consumer implementation |
MessageWeaver.SourceGenerator |
Roslyn source generator for handler discovery and registration |
dotnet add package MessageWeaver.AzureServiceBus
The Abstractions and SourceGenerator packages are pulled in transitively.
Quick start
1. Define a message
using MessageWeaver.Abstractions;
using MessageWeaver.Abstractions.Attributes;
[Message("orders", MessageType.Queue)]
public class OrderCreatedEvent : IMessage
{
public Guid OrderId { get; init; }
public decimal Amount { get; init; }
public string CustomerName { get; init; } = string.Empty;
}
The [Message] attribute tells the source generator that this message should be published to a queue named orders. Use MessageType.Topic for pub/sub scenarios.
2. Define a handler
using MessageWeaver.Abstractions;
using MessageWeaver.Abstractions.Attributes;
[QueueHandler("orders")]
public class OrderCreatedEventHandler : IMessageHandler<OrderCreatedEvent>
{
private readonly ILogger<OrderCreatedEventHandler> _logger;
public OrderCreatedEventHandler(ILogger<OrderCreatedEventHandler> logger)
{
_logger = logger;
}
public Task HandleAsync(
OrderCreatedEvent message,
MessageContext context,
CancellationToken cancellationToken)
{
_logger.LogInformation("Processing order {OrderId}", message.OrderId);
return Task.CompletedTask;
}
}
3. Register services
using MessageWeaver;
using MessageWeaver.AzureServiceBus.Extensions;
var builder = Host.CreateApplicationBuilder(args);
// Register source-generated handlers and handler factory
builder.Services.AddGeneratedMessageHandlers();
// Register Azure Service Bus publisher
builder.Services.AddAzureServiceBusPublisher(builder.Configuration);
// Register Azure Service Bus consumer
builder.Services.AddAzureServiceBusConsumer(builder.Configuration);
4. Configure connection
{
"MessageWeaver": {
"AzureServiceBus": {
"ConnectionString": "Endpoint=sb://your-namespace.servicebus.windows.net/;SharedAccessKeyName=...;SharedAccessKey=...",
"Retry": {
"MaxRetryAttempts": 3,
"UseExponentialBackoff": true,
"UseJitter": true
}
}
}
}
5. Publish messages
public class OrderService
{
private readonly IMessagePublisher _publisher;
public OrderService(IMessagePublisher publisher)
{
_publisher = publisher;
}
public async Task CreateOrderAsync(Order order, CancellationToken ct)
{
var evt = new OrderCreatedEvent
{
OrderId = order.Id,
Amount = order.Total,
CustomerName = order.CustomerName
};
await _publisher.PublishAsync(evt, ct);
}
}
6. Start consuming
The consumer starts and stops automatically with the host. AddAzureServiceBusConsumer registers an IHostedService that manages the consumer lifecycle.
var host = builder.Build();
await host.RunAsync();
Features
Consumer lifecycle
By default the consumer starts automatically with the host. To manage the lifecycle manually, set Consumer.AutoStart = false:
builder.Services.AddAzureServiceBusConsumer(options =>
{
options.Consumer.AutoStart = false;
});
Or via configuration:
{
"MessageWeaver": {
"AzureServiceBus": {
"Consumer": {
"AutoStart": false
}
}
}
}
Then resolve IMessageConsumer and call StartAsync/StopAsync directly:
var consumer = host.Services.GetRequiredService<IMessageConsumer>();
await consumer.StartAsync(cancellationToken);
Topic subscriptions (pub/sub)
Publish to a topic and consume from subscriptions. Multiple services can independently subscribe to the same topic.
[Message("order-events", MessageType.Topic)]
public class InventoryReservedEvent : IMessage
{
public Guid OrderId { get; init; }
public string ProductSku { get; init; } = string.Empty;
public int Quantity { get; init; }
}
[SubscriptionHandler("order-events", "warehouse-service")]
public class WarehouseHandler : IMessageHandler<InventoryReservedEvent>
{
public Task HandleAsync(
InventoryReservedEvent message,
MessageContext context,
CancellationToken cancellationToken)
{
// ...
}
}
Subscription handlers support SQL filters, auto-creation, dead-letter processing, and concurrency control:
[SubscriptionHandler("order-events", "high-value-orders",
SqlFilter = "Amount > 1000",
AutoCreateSubscription = true,
MaxConcurrentMessages = 5)]
Publish options
Control message delivery with PublishOptions:
await publisher.PublishAsync(evt, PublishOptions.WithCorrelationId(correlationId), ct);
await publisher.PublishAsync(evt,
PublishOptions.WithScheduledDelivery(DateTimeOffset.UtcNow.AddMinutes(30)), ct);
await publisher.PublishAsync(evt, PublishOptions.WithSessionId(sessionId), ct);
await publisher.PublishAsync(evt, new PublishOptions
{
CorrelationId = correlationId,
TimeToLive = TimeSpan.FromHours(1),
PartitionKey = tenantId,
CustomProperties = new Dictionary<string, object>
{
["TenantId"] = tenantId,
["Priority"] = "high"
}
}, ct);
Batch publishing
Publish multiple messages in a single operation. Messages are automatically batched per destination and split across Azure Service Bus message batches as needed.
var events = orders.Select(o => new OrderCreatedEvent { OrderId = o.Id });
BatchPublishResult result = await publisher.PublishBatchAsync(events, ct);
if (result.IsPartialFailure)
{
foreach (var failure in result.Failures)
{
logger.LogError(failure.Exception, "Failed at index {Index}: {Reason}",
failure.Index, failure.Reason);
}
}
Heterogeneous publishing
IMessagePublisher accepts any IMessage, so you can publish mixed message types in a single batch:
public class OutboxProcessor
{
private readonly IMessagePublisher _publisher;
public async Task FlushAsync(IEnumerable<IMessage> pending, CancellationToken ct)
{
var result = await _publisher.PublishBatchAsync(pending, ct);
}
}
Multi-namespace failover
Configure multiple connection strings for publisher or consumer failover across Azure Service Bus namespaces:
{
"MessageWeaver": {
"AzureServiceBus": {
"PublisherConnectionStrings": [
"Endpoint=sb://primary.servicebus.windows.net/;...",
"Endpoint=sb://secondary.servicebus.windows.net/;..."
],
"ConsumerConnectionStrings": [
"Endpoint=sb://primary.servicebus.windows.net/;...",
"Endpoint=sb://secondary.servicebus.windows.net/;..."
]
}
}
}
When the primary namespace fails after retries, the publisher automatically attempts the next namespace in the list.
Distributed tracing
MessageWeaver integrates with System.Diagnostics.Activity for OpenTelemetry-compatible distributed tracing. Trace context (traceparent/tracestate) is automatically propagated through message properties.
Access correlation context anywhere in your handler pipeline:
using MessageWeaver.Abstractions.Diagnostics;
var correlationId = MessageContextAccessor.CurrentCorrelationId;
var causationId = MessageContextAccessor.CurrentCausationId;
var messageId = MessageContextAccessor.CurrentMessageId;
The activity source name is MessageWeaver and can be subscribed to with any OpenTelemetry-compatible collector.
MessageWeaver span names are stable:
messageweaver.publishmessageweaver.consumemessageweaver.handle
Observability contract
MessageWeaver exposes a stable telemetry contract covering structured log events, failure classification, message dispositions, and metrics. All event IDs, field names, and metric keys are guaranteed stable across releases.
Full contract details are documented in docs/observability.md.
Unmatched message handling
Customize behavior when a message arrives with no registered handler:
public class CustomUnmatchedHandler : IUnmatchedMessageHandler
{
public Task<UnmatchedMessageResult> HandleUnmatchedMessageAsync(
UnmatchedMessageContext context,
CancellationToken cancellationToken)
{
// Options: DeadLetter, Complete, Abandon, Defer
return Task.FromResult(
UnmatchedMessageResult.DeadLetter("NoHandler", $"No handler for {context.MessageTypeName}"));
}
}
Register your implementation before calling AddAzureServiceBusConsumer to override the default (which dead-letters unmatched messages).
Source generator diagnostics
The source generator reports compile-time errors and warnings:
| Code | Severity | Description |
|---|---|---|
| MW001 | Error | Duplicate queue handler for the same queue and message type |
| MW002 | Error | Duplicate subscription handler for the same topic, subscription, and message type |
| MW003 | Error | Handler class does not implement IMessageHandler<TMessage> |
| MW004 | Error | [Message] attribute has an empty destination name |
| MW005 | Error | Invalid [Message] attribute parameter |
| MW006 | Error | [Message] attribute applied to a class that does not implement IMessage |
| MW007 | Warning | Class implements IMessageHandler but has no [QueueHandler] or [SubscriptionHandler] attribute |
Configuration reference
All options are under the MessageWeaver:AzureServiceBus configuration section.
Connection
| Property | Type | Default | Description |
|---|---|---|---|
ConnectionString |
string |
null |
Azure Service Bus connection string. Used for both publishing and consuming if specific lists are not set. |
FullyQualifiedNamespace |
string |
null |
Fully qualified namespace (e.g., your-ns.servicebus.windows.net). Used with Azure Identity. |
PublisherConnectionStrings |
string[] |
[] |
Connection strings for publishing. Enables multi-namespace failover. |
ConsumerConnectionStrings |
string[] |
[] |
Connection strings for consuming. Enables multi-namespace failover. |
At least one of ConnectionString, FullyQualifiedNamespace, PublisherConnectionStrings, or ConsumerConnectionStrings must be configured.
Publisher
| Property | Type | Default | Description |
|---|---|---|---|
MaxConcurrentSends |
int |
10 |
Maximum concurrent send operations. |
BatchSizeLimit |
int |
262144 |
Maximum batch size in bytes (256 KB). |
EnableDiagnostics |
bool |
true |
Enable OpenTelemetry-compatible distributed tracing. |
When diagnostics are disabled, MessageWeaver suppresses diagnostics-controlled spans and still emits failure/critical logs.
Retry
Nested under Retry:
| Property | Type | Default | Description |
|---|---|---|---|
MaxRetryAttempts |
int |
3 |
Maximum retry attempts per namespace. |
InitialDelay |
TimeSpan |
00:00:01 |
Delay before the first retry. |
MaxDelay |
TimeSpan |
00:00:30 |
Maximum delay between retries. |
UseExponentialBackoff |
bool |
true |
Use exponential backoff vs. fixed delay. |
UseJitter |
bool |
true |
Add randomization to prevent thundering herd. |
Consumer
Nested under Consumer:
| Property | Type | Default | Description |
|---|---|---|---|
AutoStart |
bool |
true |
Start the consumer automatically with the host via IHostedService. Set to false to manage the consumer lifecycle manually. |
MaxConcurrentCalls |
int |
1 |
Maximum concurrent message processing calls. |
PrefetchCount |
int |
0 |
Number of messages to prefetch from the broker. |
MaxAutoLockRenewalDuration |
TimeSpan |
00:05:00 |
Maximum duration for automatic lock renewal. |
Infrastructure auto-creation
| Property | Type | Default | Description |
|---|---|---|---|
AutoCreateQueuesOnPublish |
bool |
true |
Create queues automatically when publishing. |
AutoCreateTopicsOnPublish |
bool |
true |
Create topics automatically when publishing. |
AutoCreateSubscriptionsOnPublish |
bool |
true |
Create subscriptions automatically when publishing. |
AutoCreateQueuesOnReceive |
bool |
true |
Create queues automatically when consuming. |
AutoCreateTopicsOnReceive |
bool |
true |
Create topics automatically when consuming. |
AutoCreateSubscriptionsOnReceive |
bool |
true |
Create subscriptions automatically when consuming. |
Infrastructure provisioning policy
| Property | Type | Default | Description |
|---|---|---|---|
Infrastructure.FailurePolicy |
enum |
WarnAndContinue |
Controls how provisioning errors are handled (WarnAndContinue, FailFast). |
Infrastructure.Mode |
enum |
OnDemand |
Controls provisioning lifecycle (OnDemand, Preflight, Off). |
Use FailFast in development and integration tests to surface topology and permission issues immediately. In production, prefer provisioning through deployment pipelines and set Infrastructure.Mode to Off.
Project structure
src/
MessageWeaver.Abstractions/ Core interfaces, attributes, diagnostics
MessageWeaver.AzureServiceBus/ Azure Service Bus implementation
MessageWeaver.SourceGenerator/ Roslyn incremental source generator
tests/
MessageWeaver.AzureServiceBus.Tests/
MessageWeaver.SourceGenerator.Tests/
MessageWeaver.Integration.Tests/
samples/
MessageWeaver.TestApp/ Working sample application
Prerequisites
- .NET 10 SDK (preview)
- An Azure Service Bus namespace (for running the sample or integration tests)
Building
dotnet restore
dotnet build
Running tests
dotnet test
To generate a code coverage report:
dotnet test --collect:"XPlat Code Coverage" --results-directory ./coverage
Contributing
Contributions are welcome. To get started:
- Fork the repository
- Create a feature branch (
git checkout -b feature/my-feature) - Make your changes
- Run the full test suite (
dotnet test) - Submit a pull request
Please ensure:
- All new code has corresponding unit tests
- The build passes with zero warnings (
TreatWarningsAsErrorsis enabled) - Code follows the existing
.editorconfigconventions
License
This project is licensed under the MIT License.
| 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
- Azure.Messaging.ServiceBus (>= 7.18.2)
- MessageWeaver.Abstractions (>= 0.1.0-alpha.2)
- Microsoft.Extensions.Azure (>= 1.7.6)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Options (>= 9.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 9.0.0)
- Polly (>= 8.5.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.0-alpha.3 | 132 | 3/10/2026 |
| 0.1.0-alpha.2 | 91 | 3/10/2026 |
| 0.1.0-alpha.1 | 100 | 3/10/2026 |