0
votes

I've been trying for a few days, and struggling with a best practice for this - any ideas?

Contrived private message example:

  • Multiple users logged into blazor server
  • Server subscribes to an event bus/message queue to receive NewMessageEvent
  • Only the user that is the intended recipient should be updated.

I can create a singleton to subscribe to the message queue. I can then use a singleton that I inject to the required blazor component to add the message to a list and issue a stateHasChanged event.

That would update all connected clients (not ideal, the service injected to the components should be scoped).

Options so far:

  • I could verify the recipient for the message inside the blazor component, but it sort of feels the wrong place
  • Subscribe to the queue once per circuit (The queue still holds all messages though)

What I was hoping to do, was possibly create a service locator based on the circuit Id and connected userId using a circuit handler, and call a function like: NewMessageReceivedFor(userId), if that finds a matched circuit, then call the scoped service function.

This means that I should call a scoped service from a singleton (not allowed by DI through the constructor), by some form of GetRequiredService, but can I get that scoped service by specifying a circuit Id?

I currently feel Im either 90% there, or in the wrong forest, let alone up the wrong tree.

1
Are you running your own SignalR Hub (aside from the Blazor one)? - Henk Holterman
No I'm not at the moment - AndyBond

1 Answers

1
votes

You could have a Singleton service for dealing with all messages, and then a Scoped service that subscribes to an event on the Singleton and then only triggers its own event if the message is for the current user (you'd need a service registered as Scoped to get the current user ID).

That way each user will only get a notification when the message is meant for them.

Don't forget to implement IDisposable on the Scoped service, so you can unsubscribe from the Singleton service.