Using Azure Service Bus for Web API asynchronous call

Adebayo A. Asamu 45 Reputation points
2024-01-06T22:43:48.8666667+00:00

Hello everyone,

I have 2 web APIs that were developed using ASP.NET Core. These are 2 independent services that carryout business functions. One is the Order API and the other Payments API

Order API calls Payment API synchronously and it works well most of the time.

We saw an increase in traffic and we are noticing timeouts resulting from this current implementation.

We are looking to move to a messaging service using Azure Service Bus.

Most examples, even on the Microsoft Documentation use Console apps.

Adding the ServiceBusSender in Order API is pretty straightforward. The challenge is on the Payment API where we have to use the ServiceBusProcessor .

The first method I have seen involves using a HostedService and setting a timer. This is not an optimal scenario for us.

The second method looks like what we want, but I want to know if this is a good way. Here is a snippet of what it looks like:

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IServiceBusConsumer, ServiceBusConsumer>();
}

public Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	var bus = app.ApplicationServices.GetService<IServiceBusConsumer>();
	bus.RegisterOrderHandler().GetAwaiter().GetResult();
}

I would like to know if this will not lead to any issues later.

Thanks

Azure Service Bus
Azure Service Bus
An Azure service that provides cloud messaging as a service and hybrid integration.
700 questions
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. hossein jalilian 10,825 Reputation points Volunteer Moderator
    2024-01-08T22:08:53.0533333+00:00

    Hello Adebayo,

    I can offer some guidance on the general approach and potential considerations:

    1- Registering the ServiceBusConsumer as a singleton service indicates that there will be a single instance of this consumer shared across the application. Ensure that your ServiceBusConsumer is designed to be thread-safe if it contains any state.

    2- Calling GetAwaiter().GetResult() synchronously is generally not recommended, especially in the startup code of your application. This might lead to deadlocks in certain scenarios. Instead, consider using the asynchronous async and await pattern, especially in the Configure method of your Startup class.

    3- Ensure that proper exception handling is in place, especially around the initialization of the Service Bus consumer. Handle exceptions gracefully and consider logging any errors for later analysis.

    4- Implement proper monitoring and logging for your Service Bus interactions. This will help you identify and troubleshoot any issues that might arise during runtime.

    best regards,

    1 person found this answer helpful.

  2. MikeUrnun 9,777 Reputation points Moderator
    2024-01-23T05:11:50.6+00:00

    Hello @Adebayo A. Asamu - You can inject ServiceBusClient as a dependency per this guidance and register Sender, and Receiver subclients in various ways. Here's one using Azure.Identity:

    public void ConfigureServices(IServiceCollection services)
     {
         services.AddAzureClients(builder =>
         {
             // This will register the ServiceBusClient using an Azure Identity credential.
             builder.AddServiceBusClientWithNamespace("<<YOUR NAMESPACE>>.servicebus.windows.net");
    
             // By default, DefaultAzureCredential is used, which is likely desired for most
             // scenarios. If you need to restrict to a specific credential instance, you could
             // register that instance as the default credential instead.
             builder.UseCredential(new ManagedIdentityCredential());
         });
    
         // Register other services, controllers, and other infrastructure.
     }
    
    
    

    Here's another example: https://learn.microsoft.com/en-us/dotnet/azure/sdk/dependency-injection?tabs=web-app-builder#register-clients-and-subclients Could you elaborate on setting a timer when using HostedService? The following sample creates two APIs communicating via Service Bus: https://github.com/damienbod/AspNetCoreServiceBus/tree/main

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.