Dapr doc shows how to programmatically subscribe and consume a topic from a subscription, along with an ASP.NET Web API project.
I am using Azure Service Bus Topics and an Web API running in .NET 8.
I define the connection string for the Azure Service Bus and the subscription name (in consumerID metadata key value) in the yaml file:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: dapr-pubsub-component
spec:
type: pubsub.azure.servicebus.topics
version: v1
metadata:
- name: connectionString
value: [YOUR_SERVICE_BUS_CONNECTION_STRING]
- name: consumerID
value: dapr-demo-subscription-1
Then in the Web API project, I install Dapr.AspNetCore Nuget, and add Dapr into the MVC pipeline by:
public class Program
{
public static void Main(string[] args)
{
...
builder.Services.AddControllers()
.AddDapr();
...
}
}
And then I defined a controller and an action denoted to handle any topics from the subscription I defined in yaml file at the beginning:
[ApiController]
[Route("api/vehicles")]
public class VehicleSubscriberController : ControllerBase
{
// "dapr-pubsub-component" is the pubsub component name I defined in the yaml
// "vehicle-created-topic" is the topic name I subscribe
[Topic("dapr-pubsub-component", "vehicle-created-topic")]
[HttpPost("")]
public IActionResult VehicleCreated(VehicleCreated @event)
{
if (@event is not null)
{
// Handle the event
return Ok();
}
return BadRequest();
}
[Topic("dapr-pubsub-component", "vehicle-ownership-changed-topic")]
[HttpPatch("/{vehicleId}/ownership")]
...
}
Lastly, when I run the dapr run command:
dapr run
--app-id dapr-subscriber-demo
--app-port 5219
--resources-path ..\..\components\pubsub\azure\servicebus\topics\
-- dotnet run
I can see from the logs that the events have been consumed.
This is working great, and I can add as many controllers and actions I want, to consume as many topics I want, as long as they're coming from the same subscription dapr-demo-subscription-1.
But how can I consume different topics from a different subscription from the same Azure Service Bus? And I want to keep all the consumers in the same Web API project.