Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where Should NotificationHubClient be instantiated?

I am experimenting with Azure Notification Bus, and my goal is to have a WebApi service sending push notifications upon specific events triggered by controller actions.

I was wondering where would be the correct place to instantiate the NotificationHubClient object.
I assume it could be either in the controller (right before sending the notification), or instead it could be globally initialized (like in the App_Start) and re-used in the controllers.

In this example tutorial, the NotificationHubClient is instantiated in the controller:

public RegisterController()
{
    var cn = "<FULL_SAS_CONNECTION_STRING>";
    hubClient = NotificationHubClient(cn, "<NOTIFICATION_HUB_NAME>");
}

What would be the preferred way?

like image 666
Liel Avatar asked Mar 23 '23 13:03

Liel


2 Answers

I would think that you'd want to instantiate this in the controller. Unlike the QueueClient and SubscriptionClient classes the instance members of the NotificationHubClient are not guaranteed to be Threadsafe according to the docs. This means that if you had a global instance and used it during multiple request processing that they may not interact well.

like image 142
MikeWo Avatar answered Apr 02 '23 00:04

MikeWo


Good question! As MikeWo states, it is not documented as thread-safe. But if you look at the Azure WebJobs SDK, they actually cache the client per (connection string, hub name) combination. So either Microsoft itself is doing something wrong here, or the client is in fact thread-safe and just poorly documented.

like image 21
Søren Boisen Avatar answered Apr 02 '23 02:04

Søren Boisen