Since SignalR has been integrated within ASP.NET Core, it is not possible any more to use one connection for multiple hubs:
In ASP.NET Core SignalR, the connection model has been simplified. Connections are made directly to a single hub, rather than a single connection being used to share access to multiple hubs.
As a workaround for a god class, you could make use of #region
's to structure your code, if you want to use a single hub.
However, I do recommend to use different hubs for each purpose. For example: if I have a chat system, I would use a specific hub (ChatHub
) for the chat. If I also have a quiz system, I would use a QuizHub
, etc...
I don't really see the problem of handling multiple connections. Because there will be no performance issues. By seperating the code for each purpose, you are implementing separation of concerns (correct me if I'm wrong).
If you can, only initialize the client code (connection) on the pages where you actually use it, by dividing the SignalR client code (per hub) into its own file.
Let's take my last example: if the quiz has its own page, only load the SignalR client-side code on that page only.
Another thing you could try, is AJAX requests. Sometimes, I separate my code into different API controllers, and simply make an AJAX request to my API controller, to handle database transactions, for example.
You can also use some SignalR features inside that controller, by using IHubContext<T>
.
In ASP.NET Core SignalR, you can access an instance of IHubContext via dependency injection. You can inject an instance of IHubContext into a controller, middleware, or other DI service. Use the instance to send messages to clients.
class SomeController : Controller
{
private readonly IHubContext<MyHub> _hubContext;
public SomeController(IHubContext<MyHub> hubContext)
{
_hubContext = hubContext;
}
}
The documentation of using SignalR functions outside the hub, has more examples.
The downside is that you can't use all the nice features of SignalR, like adding connections to groups. It is possible to use the within your controller.