question

GregoryBologna-9283 avatar image
0 Votes"
GregoryBologna-9283 asked RoyLi-MSFT edited

SignalR MVVM UWP or WinUI 3

I’m looking for examples on how to do SignalR MVVM in C#. I don’t know how to receive SignalR messages in a ViewModel.

Basically, I have developed several single page C# UWP apps with SignalR ASP.NET Core all without using the MVVM pattern. I am now designing a new app using WinUI 3 desktop—though I may go back to UWP because the new WinUI 3 is a bit challenging and I don’t have a lot of time. Either way, the new app will have multiple xaml pages, so I would like to use MVVM. The app will receive server messages that will fill a WinUI control DataGrid.

windows-uwpdotnet-aspnet-general
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RoyLi-MSFT avatar image
0 Votes"
RoyLi-MSFT answered RoyLi-MSFT edited

Hello,

Welcome to Microsoft Q&A!

MVVM doesn't have an effect on how you receive the SingalR messages. Just do what you do in your previous apps and put these codes into a method inside the ViewModel. For example, you have a socket connection method and a message receive method, then put them into the ViewModel and call them when you want.

Thank you.


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

That is easy enough. Thanks. I want to open the connection when the app is first launched and keep it open so the app can continue to receive messages from the server. Think of my app as a stock watch that continually gets messages from the server, and can also make requests for certain data. The connection will auto connect if connection is lost using WithAutomaticReconnect. There will be many ViewModels using the same HubConnection. What is the best way to handle this? Should I put the open connection work in App.xaml.cs OnLaunched and close connection in OnSuspending?

 // PersonViewModel 
     
 // Get open Connection 
 private HubConnection connection { get; } = ((App)Application.Current).Connection; 
     
 // receive message from server - connection  
 connection.On<List<PersonType>>("PersonList", (m) => PersonMethod(m)); 
     
 private async void PersonMethod(List<PersonType> person) {  
  // do work 
 }
0 Votes 0 ·
RoyLi-MSFT avatar image RoyLi-MSFT GregoryBologna-9283 ·

@GregoryBologna-9283 It is a common way to put your connect method into the OnLaunched event. And you could put the receive method into detailed pages. This could make sure your connection is established as soon as the app is launched.

1 Vote 1 ·