Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top