Where Should NotificationHubClient be instantiated?
Asked Answered
B

2

5

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?

Buttocks answered 2/9, 2013 at 11:0 Comment(0)
N
5

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.

Narrows answered 2/9, 2013 at 13:12 Comment(1)
Thanks @Zapnologica. Corrected.Narrows
S
2

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.

Spirketing answered 9/1, 2017 at 12:58 Comment(3)
It's quite possible they're keeping the option open to make it thread unsafe in future. In which case it wouldn't be a breaking change - unless you've assumed it is thread safe. So be careful.Kaluga
The link "cache the client" is dead, and i searched the entire repo for "notification" and "hub" and the example, and even anything about azure notificationhub has been purged from that repo.Statuesque
@Statuesque Hm mysterious. I cannot figure out where the source code for notification hubs extension went and no trace in issues or pull requests about the move. According to the README, the extension should still be supported.Chintz

© 2022 - 2024 — McMap. All rights reserved.