Перейти к содержимому
Docs Try Aspire
Docs Try

Connect to Azure Event Hubs

Это содержимое пока не доступно на вашем языке.

Azure Event Hubs logo

This page describes how consuming apps connect to an Azure Event Hubs resource that’s already modeled in your AppHost. For the AppHost API surface — adding a namespace, hubs, consumer groups, the emulator, and more — see Azure Event Hubs Hosting integration.

When you reference an Azure Event Hubs resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire Azure Messaging Event Hubs client integration for automatic dependency injection, health checks, and telemetry.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called event-hubs becomes EVENT_HUBS_URI.

The Event Hubs namespace resource exposes the following connection properties:

Property NameDescription
HostThe hostname of the Event Hubs namespace
PortThe port of the Event Hubs namespace (emulator only)
UriThe connection URI, with the format sb://myeventhubs.servicebus.windows.net on Azure and sb://localhost:62824 for the emulator
ConnectionStringEmulator only. Full connection string including SAS key material for the local emulator

Example connection strings:

Uri: sb://myeventhubs.servicebus.windows.net
ConnectionString: Endpoint=sb://localhost:62824;SharedAccessKeyName=... (emulator only)

The Event Hub resource inherits all properties from its parent namespace and adds:

Property NameDescription
EventHubNameThe name of the Event Hub

The Event Hub consumer group resource inherits all properties from its parent hub and adds:

Property NameDescription
ConsumerGroupNameThe name of the consumer group

For example, if you add a hub named messages and reference it from a consuming app, the following environment variables are available:

  • MESSAGES_HOST
  • MESSAGES_URI
  • MESSAGES_EVENTHUBNAME

Pick the language your consuming app is written in. Each example assumes your AppHost adds an Azure Event Hubs namespace named event-hubs with a hub named messages, and references them from the consuming app.

For C# apps, the recommended approach is the Aspire Azure Messaging Event Hubs client integration. It registers strongly-typed Event Hubs client instances through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.

Install the 📦 Aspire.Azure.Messaging.EventHubs NuGet package in the client-consuming project:

.NET CLI — Add Aspire.Azure.Messaging.EventHubs package
dotnet add package Aspire.Azure.Messaging.EventHubs

The following Event Hubs client types are supported, along with their corresponding options and settings classes:

Azure client typeAzure options classAspire settings class
EventHubProducerClientEventHubProducerClientOptionsAzureMessagingEventHubsProducerSettings
EventHubBufferedProducerClientEventHubBufferedProducerClientOptionsAzureMessagingEventHubsBufferedProducerSettings
EventHubConsumerClientEventHubConsumerClientOptionsAzureMessagingEventHubsConsumerSettings
EventProcessorClientEventProcessorClientOptionsAzureMessagingEventHubsProcessorSettings
PartitionReceiverPartitionReceiverOptionsAzureMessagingEventHubsPartitionReceiverSettings

In Program.cs, call AddAzureEventHubProducerClient to register an EventHubProducerClient:

C# — Program.cs
builder.AddAzureEventHubProducerClient(connectionName: "messages");

Resolve the client through dependency injection:

C# — ExampleService.cs
public class ExampleService(EventHubProducerClient producerClient)
{
// Use producerClient...
}

To consume events, register an EventProcessorClient:

C# — Program.cs
builder.AddAzureEventProcessorClient(connectionName: "messages");

Resolve it through dependency injection:

C# — ExampleService.cs
public class ExampleService(EventProcessorClient processorClient)
{
// Use processorClient...
}

When you need to register a different client type, use the corresponding API:

Azure client typeRegistration API
EventHubProducerClientAddAzureEventHubProducerClient
EventHubBufferedProducerClientAddAzureEventHubBufferedProducerClient
EventHubConsumerClientAddAzureEventHubConsumerClient
EventProcessorClientAddAzureEventProcessorClient
PartitionReceiverAddAzurePartitionReceiverClient

To register multiple client instances with different connection names, use the keyed APIs:

C# — Program.cs
builder.AddKeyedAzureEventHubProducerClient(name: "messages");
builder.AddKeyedAzureEventHubProducerClient(name: "commands");

Then resolve each instance by key:

C# — ExampleService.cs
public class ExampleService(
[KeyedService("messages")] EventHubProducerClient messagesClient,
[KeyedService("commands")] EventHubProducerClient commandsClient)
{
// Use clients...
}

The full set of keyed registration APIs:

Azure client typeKeyed registration API
EventHubProducerClientAddKeyedAzureEventHubProducerClient
EventHubBufferedProducerClientAddKeyedAzureEventHubBufferedProducerClient
EventHubConsumerClientAddKeyedAzureEventHubConsumerClient
EventProcessorClientAddKeyedAzureEventProcessorClient
PartitionReceiverAddKeyedAzurePartitionReceiverClient

For more information, see Keyed services in .NET.

The Aspire Azure Messaging Event Hubs library supports multiple configuration approaches. Either a FullyQualifiedNamespace or a ConnectionString is required.

Fully Qualified Namespace (recommended). Use a fully qualified namespace with the default credential:

JSON — appsettings.json
{
"ConnectionStrings": {
"messages": "{your_namespace}.servicebus.windows.net"
}
}

If no credential is configured, a default credential is used.

Connection string. Alternatively, provide a full connection string:

JSON — appsettings.json
{
"ConnectionStrings": {
"messages": "Endpoint=sb://mynamespace.servicebus.windows.net/;SharedAccessKeyName=accesskeyname;SharedAccessKey=accesskey;EntityPath=messages"
}
}

Configuration providers. The library loads AzureMessagingEventHubsSettings and the associated client options from the Aspire:Azure:Messaging:EventHubs: key prefix, followed by the specific client name. For example, to configure an EventProcessorClient:

JSON — appsettings.json
{
"Aspire": {
"Azure": {
"Messaging": {
"EventHubs": {
"EventProcessorClient": {
"EventHubName": "messages",
"ClientOptions": {
"Identifier": "PROCESSOR_ID"
}
}
}
}
}
}
}

Named configuration. To configure multiple instances of the same client type with different settings, use named configuration:

JSON — appsettings.json
{
"Aspire": {
"Azure": {
"Messaging": {
"EventHubs": {
"EventProcessorClient": {
"processor1": {
"EventHubName": "messages",
"ClientOptions": { "Identifier": "PROCESSOR_1" }
},
"processor2": {
"EventHubName": "commands",
"ClientOptions": { "Identifier": "PROCESSOR_2" }
}
}
}
}
}
}
}

Then use the connection names when registering:

C# — Program.cs
builder.AddAzureEventProcessorClient("processor1");
builder.AddAzureEventProcessorClient("processor2");

Inline delegates. Pass an Action<IAzureClientBuilder<...>> to configure the client builder inline:

C# — Program.cs
builder.AddAzureEventProcessorClient(
"messages",
configureClientBuilder: clientBuilder => clientBuilder.ConfigureOptions(
options => options.Identifier = "PROCESSOR_ID"));

For the complete JSON schema, see Aspire.Azure.Messaging.EventHubs/ConfigurationSchema.json.

Aspire client integrations enable health checks by default. The Azure Messaging Event Hubs client integration registers a health check that verifies connectivity to the namespace. The health check is wired into the /health HTTP endpoint.

The Aspire Azure Messaging Event Hubs client integration automatically configures logging, tracing, and metrics through OpenTelemetry.

Logging categories:

  • Azure.Core
  • Azure.Identity

Tracing activities:

  • Azure.Messaging.EventHubs.*

Metrics: The Azure Messaging Event Hubs client integration currently doesn’t support metrics by default due to limitations with the Azure SDK for .NET. This section will be updated if that changes.

If you prefer not to use the Aspire client integration, you can read the connection URI from the environment and use the Azure SDK directly:

C# — Program.cs
using Azure.Messaging.EventHubs.Producer;
var fullyQualifiedNamespace = Environment.GetEnvironmentVariable("EVENT_HUBS_HOST");
var eventHubName = Environment.GetEnvironmentVariable("MESSAGES_EVENTHUBNAME");
var producer = new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, new DefaultAzureCredential());
// Use producer to send events...