The infrastructure is the following:
- ASP.NET MVC app on one server
- ASP.NET Web Api 2 on second server
- SignalR with multiple Hubs on thirth server
When some controller action is executed on the WebApi I need to send request to the SignalR server and invoke some Hubs methods. Often I need to invoke multiple different methods from one or more hubs in single WebApi request. What I do now is create new HubConnection and create HubProxy for every Hub method that I need to invoke in a singe request, so if I need to invoke 5 different hub methods I create 5 different connections. I doubt this is the right way to manage the HubConnection. Should I create only one HubConnection per each WebApi request or should I keep only one HubConnection per application lifetime (All api requests use one instance).
public class HubsConnectionManager
{
//private static HubConnection hubConneciton; - Use this for per application singleton
//private HubConnection hubConnection; - Use this for per request singleton
public async Task<IHubProxy> GetHub<THub>() where THub : Hub
{
var hubConnection = new HubConnection("http://localhost:51489/");
string hubName = typeof(THub).Name;
IHubProxy hub = hubConnection.CreateHubProxy(hubName);
await hubConnection.Start();
return hub;
}
}
HubsConnectionManager manager; // HubsConnectionManager is a singleton per request
IHubProxy hub = await manager.GetHub<NotificationHub>();
await hub.Invoke("PushNotificationToUser", notificaiton);
If I were to implement the per request singleton solution I would add private HubConnection member in the HubsConnectionManager and if I were to implement the per application solution, I would add private static HubConnection and use them in the GetHub method. Which solution is the right one and how should I implement it? How should I handle the situations when the connection has been lost?