4

I was just wondering why the recommended solution for a Blazor-Server-Chat by Microsoft is initializing a Signal R Hub. Technically, all the C# Code is executed on the server, so it's also possible to realize the chat with a singleton:

public class MySingleton
{
    public event Action<string> OnBroadcast
    public void Send(string msg)
    {
        OnBroadcast.Invoke(msg);
    }
}

In the Blazor-Component I consume this singleton, subscribe to the event, and call Send(...).

Why I should realize this Chat with a separate SignalR Hub?

Rob
  • 14,746
  • 28
  • 47
  • 65
Johnny S.
  • 41
  • 1
  • This SO question might help: [Why choose Hub vs. Persistent Connection?](https://stackoverflow.com/questions/9280484/signalr-why-choose-hub-vs-persistent-connection) and [How to get SignalR Hub Context](https://stackoverflow.com/questions/27299289/how-to-get-signalr-hub-context-in-a-asp-net-core?rq=1) Apparently you should use IHubContext. – Yogi Apr 26 '22 at 13:23
  • I guess it is just an academical example because it has no sense. Good point. – dani herrera Apr 26 '22 at 13:50
  • @Yogi But due to Blazor-Server I have a persistent connection anyway. So why initializing an additional hub. – Johnny S. Apr 27 '22 at 08:14
  • The advantages of using a dedicated hub becomes clear when you research it. This Microsoft article outlines some of the advantages: [Use hubs in SignalR](https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-6.0) Good question though as I'd not dug into this topic until now. – Yogi Apr 27 '22 at 09:07
  • I notice that the sample is not a Blazor example, it is from the SignalR docs. So yes, it looks rather pointless. Unless when you were to scale-out your app to multiple servers. – H H May 03 '22 at 10:44
  • I noticed using a dedicated Hub has also the advantage that it's easier to port the app to Blazor WebAssembly Application later – Johnny S. May 06 '22 at 07:05

1 Answers1

0

In the document you linked, Microsoft isn't recommending you use a normal SignalR Hub for a chat application, they are providing documentation on how you can use Azure SignalR Service; a paid Azure service that simplifies using SignalR across multiple server instances. With a singleton you don't need a hub, but it won't work if your web app has multiple instances behind a load balancer.

If you only have one web app instance and you will never expand to additional instances, then the singleton approach would probably work fine.

keithwill
  • 1,964
  • 1
  • 17
  • 26