azure-servicebus-dotnet
Azure Service Bus SDK for .NET. Enterprise messaging with queues, topics, subscriptions, and sessions.
About this skill
This skill equips AI agents with the essential knowledge and setup guidance to interact with Azure Service Bus using its official .NET SDK. It facilitates the implementation of robust enterprise messaging patterns, including point-to-point communication with queues, publish-subscribe models via topics and subscriptions, and ordered message processing using sessions. By detailing installation procedures, environment variable configuration, and secure authentication methods like Microsoft Entra ID, this skill enables agents to programmatically manage and utilize Azure Service Bus. It's particularly valuable for agents capable of generating, analyzing, or modifying .NET applications that depend on cloud messaging for asynchronous communication and workflow orchestration.
Best use case
Automating the creation or management of Azure Service Bus entities (queues, topics, subscriptions); Assisting developers in creating or debugging .NET applications that leverage Azure Service Bus; Enabling an AI agent to send or receive messages from Azure Service Bus queues/topics based on user commands or event triggers; Integrating disparate backend services asynchronously within a .NET ecosystem.
Azure Service Bus SDK for .NET. Enterprise messaging with queues, topics, subscriptions, and sessions.
An AI agent capable of generating, analyzing, or interacting with .NET code that successfully performs operations with Azure Service Bus (e.g., sending messages, receiving messages, managing entities); A properly configured .NET project with the Azure Service Bus SDK, ready for messaging functionalities; Secure authentication to Azure Service Bus via recommended methods like Microsoft Entra ID.
Practical example
Example input
Generate C# code to send a simple text message 'System Update Required' to an Azure Service Bus queue named 'system-notifications', using Microsoft Entra ID for authentication.
Example output
```csharp
// This code assumes the AZURE_SERVICEBUS_FULLY_QUALIFIED_NAMESPACE environment variable is set.
// For Microsoft Entra ID authentication, ensure your application or user has appropriate permissions.
using Azure.Messaging.ServiceBus;
using Azure.Identity;
using System;
using System.Threading.Tasks;
public class SystemNotificationSender
{
public static async Task Main(string[] args)
{
string fullyQualifiedNamespace = Environment.GetEnvironmentVariable("AZURE_SERVICEBUS_FULLY_QUALIFIED_NAMESPACE");
if (string.IsNullOrEmpty(fullyQualifiedNamespace))
{
Console.WriteLine("Error: AZURE_SERVICEBUS_FULLY_QUALIFIED_NAMESPACE environment variable is not set.");
return;
}
string queueName = "system-notifications";
string messageBody = "System Update Required";
// Create a ServiceBusClient using Microsoft Entra ID authentication
await using var client = new ServiceBusClient(fullyQualifiedNamespace, new DefaultAzureCredential());
// Create a sender for the specified queue
ServiceBusSender sender = client.CreateSender(queueName);
try
{
// Create a message
ServiceBusMessage message = new ServiceBusMessage(messageBody);
// Send the message to the queue
await sender.SendMessageAsync(message);
Console.WriteLine($"Successfully sent message: '{messageBody}' to queue: '{queueName}'");
}
catch (Exception ex)
{
Console.WriteLine($"Error sending message: {ex.Message}");
}
finally
{
// Ensure the sender and client are closed and disposed properly
await sender.CloseAsync();
await client.DisposeAsync();
}
}
}
```When to use this skill
- When an AI agent needs to perform messaging operations (send, receive, manage) with Azure Service Bus in a .NET application context; When building or managing event-driven architectures where reliable, asynchronous messaging is crucial; When an agent is tasked with assisting a developer with .NET code related to Azure Service Bus; For scenarios requiring robust, decoupled communication between components in Azure-hosted services.
When not to use this skill
- When the target application or environment is not based on .NET; When simple, synchronous HTTP communication is sufficient and messaging overhead is undesirable; For extremely low-latency, high-throughput streaming data scenarios where Azure Event Hubs might be more suitable; If the AI agent lacks the capability to generate code, manage environment variables, or oversee package installations.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/azure-servicebus-dotnet/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How azure-servicebus-dotnet Compares
| Feature / Agent | azure-servicebus-dotnet | Standard Approach |
|---|---|---|
| Platform Support | Claude, ChatGPT, Gemini, Cursor, GitHub Copilot, DeepSeek, Aider, Continue | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | medium | N/A |
Frequently Asked Questions
What does this skill do?
Azure Service Bus SDK for .NET. Enterprise messaging with queues, topics, subscriptions, and sessions.
Which AI agents support this skill?
This skill is designed for Claude, ChatGPT, Gemini, Cursor, GitHub Copilot, DeepSeek, Aider, Continue.
How difficult is it to install?
The installation complexity is rated as medium. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
Cursor vs Codex for AI Workflows
Compare Cursor and Codex for AI coding workflows, repository assistance, debugging, refactoring, and reusable developer skills.
SKILL.md Source
# Azure.Messaging.ServiceBus (.NET)
Enterprise messaging SDK for reliable message delivery with queues, topics, subscriptions, and sessions.
## Installation
```bash
dotnet add package Azure.Messaging.ServiceBus
dotnet add package Azure.Identity
```
**Current Version**: v7.20.1 (stable)
## Environment Variables
```bash
AZURE_SERVICEBUS_FULLY_QUALIFIED_NAMESPACE=<namespace>.servicebus.windows.net
# Or connection string (less secure)
AZURE_SERVICEBUS_CONNECTION_STRING=Endpoint=sb://...
```
## Authentication
### Microsoft Entra ID (Recommended)
```csharp
using Azure.Identity;
using Azure.Messaging.ServiceBus;
string fullyQualifiedNamespace = "<namespace>.servicebus.windows.net";
await using ServiceBusClient client = new(fullyQualifiedNamespace, new DefaultAzureCredential());
```
### Connection String
```csharp
string connectionString = "<connection_string>";
await using ServiceBusClient client = new(connectionString);
```
### ASP.NET Core Dependency Injection
```csharp
services.AddAzureClients(builder =>
{
builder.AddServiceBusClientWithNamespace("<namespace>.servicebus.windows.net");
builder.UseCredential(new DefaultAzureCredential());
});
```
## Client Hierarchy
```
ServiceBusClient
├── CreateSender(queueOrTopicName) → ServiceBusSender
├── CreateReceiver(queueName) → ServiceBusReceiver
├── CreateReceiver(topicName, subName) → ServiceBusReceiver
├── AcceptNextSessionAsync(queueName) → ServiceBusSessionReceiver
├── CreateProcessor(queueName) → ServiceBusProcessor
└── CreateSessionProcessor(queueName) → ServiceBusSessionProcessor
ServiceBusAdministrationClient (separate client for CRUD)
```
## Core Workflows
### 1. Send Messages
```csharp
await using ServiceBusClient client = new(fullyQualifiedNamespace, new DefaultAzureCredential());
ServiceBusSender sender = client.CreateSender("my-queue");
// Single message
ServiceBusMessage message = new("Hello world!");
await sender.SendMessageAsync(message);
// Safe batching (recommended)
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
if (batch.TryAddMessage(new ServiceBusMessage("Message 1")))
{
// Message added successfully
}
if (batch.TryAddMessage(new ServiceBusMessage("Message 2")))
{
// Message added successfully
}
await sender.SendMessagesAsync(batch);
```
### 2. Receive Messages
```csharp
ServiceBusReceiver receiver = client.CreateReceiver("my-queue");
// Single message
ServiceBusReceivedMessage message = await receiver.ReceiveMessageAsync();
string body = message.Body.ToString();
Console.WriteLine(body);
// Complete the message (removes from queue)
await receiver.CompleteMessageAsync(message);
// Batch receive
IReadOnlyList<ServiceBusReceivedMessage> messages = await receiver.ReceiveMessagesAsync(maxMessages: 10);
foreach (var msg in messages)
{
Console.WriteLine(msg.Body.ToString());
await receiver.CompleteMessageAsync(msg);
}
```
### 3. Message Settlement
```csharp
// Complete - removes message from queue
await receiver.CompleteMessageAsync(message);
// Abandon - releases lock, message can be received again
await receiver.AbandonMessageAsync(message);
// Defer - prevents normal receive, use ReceiveDeferredMessageAsync
await receiver.DeferMessageAsync(message);
// Dead Letter - moves to dead letter subqueue
await receiver.DeadLetterMessageAsync(message, "InvalidFormat", "Message body was not valid JSON");
```
### 4. Background Processing with Processor
```csharp
ServiceBusProcessor processor = client.CreateProcessor("my-queue", new ServiceBusProcessorOptions
{
AutoCompleteMessages = false,
MaxConcurrentCalls = 2
});
processor.ProcessMessageAsync += async (args) =>
{
try
{
string body = args.Message.Body.ToString();
Console.WriteLine($"Received: {body}");
await args.CompleteMessageAsync(args.Message);
}
catch (Exception ex)
{
Console.WriteLine($"Error processing: {ex.Message}");
await args.AbandonMessageAsync(args.Message);
}
};
processor.ProcessErrorAsync += (args) =>
{
Console.WriteLine($"Error source: {args.ErrorSource}");
Console.WriteLine($"Entity: {args.EntityPath}");
Console.WriteLine($"Exception: {args.Exception}");
return Task.CompletedTask;
};
await processor.StartProcessingAsync();
// ... application runs
await processor.StopProcessingAsync();
```
### 5. Sessions (Ordered Processing)
```csharp
// Send session message
ServiceBusMessage message = new("Hello")
{
SessionId = "order-123"
};
await sender.SendMessageAsync(message);
// Receive from next available session
ServiceBusSessionReceiver receiver = await client.AcceptNextSessionAsync("my-queue");
// Or receive from specific session
ServiceBusSessionReceiver receiver = await client.AcceptSessionAsync("my-queue", "order-123");
// Session state management
await receiver.SetSessionStateAsync(new BinaryData("processing"));
BinaryData state = await receiver.GetSessionStateAsync();
// Renew session lock
await receiver.RenewSessionLockAsync();
```
### 6. Dead Letter Queue
```csharp
// Receive from dead letter queue
ServiceBusReceiver dlqReceiver = client.CreateReceiver("my-queue", new ServiceBusReceiverOptions
{
SubQueue = SubQueue.DeadLetter
});
ServiceBusReceivedMessage dlqMessage = await dlqReceiver.ReceiveMessageAsync();
// Access dead letter metadata
string reason = dlqMessage.DeadLetterReason;
string description = dlqMessage.DeadLetterErrorDescription;
Console.WriteLine($"Dead letter reason: {reason} - {description}");
```
### 7. Topics and Subscriptions
```csharp
// Send to topic
ServiceBusSender topicSender = client.CreateSender("my-topic");
await topicSender.SendMessageAsync(new ServiceBusMessage("Broadcast message"));
// Receive from subscription
ServiceBusReceiver subReceiver = client.CreateReceiver("my-topic", "my-subscription");
var message = await subReceiver.ReceiveMessageAsync();
```
### 8. Administration (CRUD)
```csharp
var adminClient = new ServiceBusAdministrationClient(
fullyQualifiedNamespace,
new DefaultAzureCredential());
// Create queue
var options = new CreateQueueOptions("my-queue")
{
MaxDeliveryCount = 10,
LockDuration = TimeSpan.FromSeconds(30),
RequiresSession = true,
DeadLetteringOnMessageExpiration = true
};
QueueProperties queue = await adminClient.CreateQueueAsync(options);
// Update queue
queue.LockDuration = TimeSpan.FromSeconds(60);
await adminClient.UpdateQueueAsync(queue);
// Create topic and subscription
await adminClient.CreateTopicAsync(new CreateTopicOptions("my-topic"));
await adminClient.CreateSubscriptionAsync(new CreateSubscriptionOptions("my-topic", "my-subscription"));
// Delete
await adminClient.DeleteQueueAsync("my-queue");
```
### 9. Cross-Entity Transactions
```csharp
var options = new ServiceBusClientOptions { EnableCrossEntityTransactions = true };
await using var client = new ServiceBusClient(connectionString, options);
ServiceBusReceiver receiverA = client.CreateReceiver("queueA");
ServiceBusSender senderB = client.CreateSender("queueB");
ServiceBusReceivedMessage receivedMessage = await receiverA.ReceiveMessageAsync();
using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await receiverA.CompleteMessageAsync(receivedMessage);
await senderB.SendMessageAsync(new ServiceBusMessage("Forwarded"));
ts.Complete();
}
```
## Key Types Reference
| Type | Purpose |
|------|---------|
| `ServiceBusClient` | Main entry point, manages connection |
| `ServiceBusSender` | Sends messages to queues/topics |
| `ServiceBusReceiver` | Receives messages from queues/subscriptions |
| `ServiceBusSessionReceiver` | Receives session messages |
| `ServiceBusProcessor` | Background message processing |
| `ServiceBusSessionProcessor` | Background session processing |
| `ServiceBusAdministrationClient` | CRUD for queues/topics/subscriptions |
| `ServiceBusMessage` | Message to send |
| `ServiceBusReceivedMessage` | Received message with metadata |
| `ServiceBusMessageBatch` | Batch of messages |
## Best Practices
1. **Use singletons** — Clients, senders, receivers, and processors are thread-safe
2. **Always dispose** — Use `await using` or call `DisposeAsync()`
3. **Dispose order** — Close senders/receivers/processors first, then client
4. **Use DefaultAzureCredential** — Prefer over connection strings for production
5. **Use processors for background work** — Handles lock renewal automatically
6. **Use safe batching** — `CreateMessageBatchAsync()` and `TryAddMessage()`
7. **Handle transient errors** — Use `ServiceBusException.Reason`
8. **Configure transport** — Use `AmqpWebSockets` if ports 5671/5672 are blocked
9. **Set appropriate lock duration** — Default is 30 seconds
10. **Use sessions for ordering** — FIFO within a session
## Error Handling
```csharp
try
{
await sender.SendMessageAsync(message);
}
catch (ServiceBusException ex) when (ex.Reason == ServiceBusFailureReason.ServiceBusy)
{
// Retry with backoff
}
catch (ServiceBusException ex)
{
Console.WriteLine($"Service Bus Error: {ex.Reason} - {ex.Message}");
}
```
## Related SDKs
| SDK | Purpose | Install |
|-----|---------|---------|
| `Azure.Messaging.ServiceBus` | Service Bus (this SDK) | `dotnet add package Azure.Messaging.ServiceBus` |
| `Azure.Messaging.EventHubs` | Event streaming | `dotnet add package Azure.Messaging.EventHubs` |
| `Azure.Messaging.EventGrid` | Event routing | `dotnet add package Azure.Messaging.EventGrid` |
## Reference Links
| Resource | URL |
|----------|-----|
| NuGet Package | https://www.nuget.org/packages/Azure.Messaging.ServiceBus |
| API Reference | https://learn.microsoft.com/dotnet/api/azure.messaging.servicebus |
| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/servicebus/Azure.Messaging.ServiceBus |
| Troubleshooting | https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/servicebus/Azure.Messaging.ServiceBus/TROUBLESHOOTING.md |
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.Related Skills
azure-storage-queue-ts
Azure Queue Storage JavaScript/TypeScript SDK (@azure/storage-queue) for message queue operations. Use for sending, receiving, peeking, and deleting messages in queues.
azure-storage-queue-py
Azure Queue Storage SDK for Python. Use for reliable message queuing, task distribution, and asynchronous processing.
azure-monitor-ingestion-java
Azure Monitor Ingestion SDK for Java. Send custom logs to Azure Monitor via Data Collection Rules (DCR) and Data Collection Endpoints (DCE).
azure-identity-py
Azure Identity SDK for Python authentication. Use for DefaultAzureCredential, managed identity, service principals, and token caching.
azure-eventgrid-py
Azure Event Grid SDK for Python. Use for publishing events, handling CloudEvents, and event-driven architectures.
azure-eventgrid-java
Build event-driven applications with Azure Event Grid SDK for Java. Use when publishing events, implementing pub/sub patterns, or integrating with Azure services via events.
azure-eventgrid-dotnet
Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents.
microsoft-azure-webjobs-extensions-authentication-events-dotnet
Microsoft Entra Authentication Events SDK for .NET. Azure Functions triggers for custom authentication extensions.
dotnet-backend
Build ASP.NET Core 8+ backend services with EF Core, auth, background jobs, and production API patterns.
dotnet-backend-patterns
Master C#/.NET patterns for building production-grade APIs, MCP servers, and enterprise backends with modern best practices (2024/2025).
dotnet-architect
Expert .NET backend architect specializing in C#, ASP.NET Core, Entity Framework, Dapper, and enterprise application patterns.
azure-web-pubsub-ts
Real-time messaging with WebSocket connections and pub/sub patterns.