WPF client - Do we create a new HubConnection for each view model, or share one around the whole application? RRS feed

  • Question

  • User-1158769213 posted


    Just getting going with SignalR and trying to integrate it into a WPF app. So far I have a view model for the main window, and have code like the following to initialise the hub connection...

        private void InitialiseHub() {
          HubConnection connection = new HubConnection(App.FerretHubUrl);
          _hubProxy = connection.CreateHubProxy("FerretHub");
          _hubProxy.On("send", msg => Log += DateTime.Now.ToLongTimeString() + " - " + msg + Environment.NewLine);
          _hubProxy.On("ferretDeleted", id => FerretDeleted(id));

    I'm now adding a second window, which has its own view model, and was about to copy the same code when it occurred to me that maybe I ought to create one HubConnection when the app starts, and have all view models use it.

    Any comments? Do I create one shared HubConnection, or have each view model create its own?


    Wednesday, March 28, 2018 9:33 PM

All replies

  • User61956409 posted

    Hi Yossu,

    maybe I ought to create one HubConnection when the app starts, and have all view models use it.

    I am not familiar with WPF, but in my opinion, the approach you mentioned: creating a shared hub connection object instance when the app starts and access&perform with that connection object in view model(s) might be feasible.

    Besides, my suggestion is that you can access that shared hub connection object and check connection status in in view model, if the connection is disconnected, you can create a new hub connection and establish a new connection to hub server.

    With Regards,

    Fei Han

    Thursday, March 29, 2018 6:18 AM
  • User-1158769213 posted

    Thanks for the reply. I tried it, and it seems to work OK.

    I hadn't thought about the disconnection issue, but a shared hub would have an advantage in that respect, in that we'd only need to reconnect once.

    Thanks for the reply.

    Thursday, March 29, 2018 5:02 PM