This sample shows how to leverage topology options to layout the topic topology used within the Application configuration. The sample uses the generic host for convenient loading of configuration via the built-in configuration provider model. The appsettings.
is used for demonstration purposes and technically the options could be loaded from other sources.
Prerequisites
An environment variable named AzureServiceBus_ConnectionString
with the connection string for the Azure Service Bus namespace.
Code walk-through
The sample contains three executable projects:
Publisher
: an NServiceBus endpoint that publishesEventOne
to topicevent-one
andEventTwo
toevent-two
.Subscriber
: an NServiceBus endpoint subscribing to theEventOne
andEventTwo
event published by thePublisher
.
Configuration from options
With the generic hosts ability to load configuration sections it is a matter of loading the topology options from the section in the Application configuration as shown below:
var section = builder.Configuration.GetSection("AzureServiceBus");
var topologyOptions = section.GetSection("Topology").Get<TopologyOptions>()!;
var topology = TopicTopology.FromOptions(topologyOptions);
endpointConfiguration.UseTransport(new AzureServiceBusTransport(section["ConnectionString"]!, topology));
In this example the publisher overrides the default topic destination to a custom conventions instead of using the default fullname of the event type:
"AzureServiceBus": {
"ConnectionString": "Endpoint=sb://...;SharedAccessKeyName=...;SharedAccessKey=...",
"Topology": {
"PublishedEventToTopicsMap": {
"Shared.EventOne": "event-one",
"Shared.EventTwo": "event-two"
}
}
}
The subscriber needs to override the subscription mapping accordingly:
"AzureServiceBus": {
"ConnectionString": "Endpoint=sb://...;SharedAccessKeyName=...;SharedAccessKey=...",
"Topology": {
"SubscribedEventToTopicsMap": {
"Shared.EventOne": ["event-one"],
"Shared.EventTwo": ["event-two"]
}
}
}
Validation
The transport provides integration with Microsoft.Extensions.Options and has a built-in options validator. With the generic host it is possible to register the validator to make sure the configuration loaded fulfills the requirements of the broker (e.g. topic name length) and is self-consistent.
services.AddSingleton<IValidateOptions<TopologyOptions>, TopologyOptionsValidator>();
services.AddOptions<TopologyOptions>().Bind(configuration.GetSection("AzureServiceBus:Topology")).ValidateOnStart();
Running the sample
- First, run the
Subscriber
project by itself. This will create all the necessary publish/subscribe infrastructure in Azure Service Bus. - Run the projects normally so that all endpoints start.
- The
Publisher
endpoint continuously publishes two events with a short pause in between.- The endpoint in the
Subscriber
window receives bothEventOne
andEventTwo
.
- The endpoint in the