Files
EngineeringSync/EngineeringSync.TrayApp/Services/SignalRService.cs

58 lines
1.8 KiB
C#
Raw Normal View History

using EngineeringSync.Domain.Constants;
using Microsoft.AspNetCore.SignalR.Client;
namespace EngineeringSync.TrayApp.Services;
public class SignalRService : IAsyncDisposable
{
private HubConnection? _connection;
public event Action<Guid, string, int>? ChangeNotificationReceived;
public event Action? ProjectConfigChanged;
public async Task ConnectAsync(CancellationToken ct = default)
{
_connection = new HubConnectionBuilder()
.WithUrl("http://localhost:5050/notifications")
.WithAutomaticReconnect([TimeSpan.Zero, TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10)])
.Build();
// Register handlers on initial connection
RegisterHandlers();
// Re-register handlers when reconnected after disconnection
_connection.Reconnected += async (connectionId) =>
{
RegisterHandlers();
await Task.CompletedTask;
};
await _connection.StartAsync(ct);
}
private void RegisterHandlers()
{
if (_connection is null)
return;
// Remove existing handlers to prevent duplicates
_connection.Remove(HubMethodNames.ReceiveChangeNotification);
_connection.Remove(HubMethodNames.ProjectConfigChanged);
// Register handlers
_connection.On<Guid, string, int>(HubMethodNames.ReceiveChangeNotification,
(projectId, projectName, count) =>
ChangeNotificationReceived?.Invoke(projectId, projectName, count));
_connection.On(HubMethodNames.ProjectConfigChanged,
() => ProjectConfigChanged?.Invoke());
}
public async ValueTask DisposeAsync()
{
if (_connection is not null)
await _connection.DisposeAsync();
}
}