using FruitBank.Common; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.SignalR.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FruitBankHybrid.Shared.Services { public class SignalRService : IAsyncDisposable, ISignalRService { private HubConnection _hubConnection; private readonly NavigationManager _navigationManager; public event Action? MessageReceived; public SignalRService(NavigationManager navigationManager) { _navigationManager = navigationManager; } public async Task InitializeAsync() { // Build the connection (assuming same domain as Blazor app, otherwise use full URL) _hubConnection = new HubConnectionBuilder() //.WithUrl(_navigationManager.ToAbsoluteUri($"https://localhost:59579/{FruitBankConstClient.DefaultHubName}")) .WithUrl(_navigationManager.ToAbsoluteUri($"{FruitBankConstClient.BaseUrl}/{FruitBankConstClient.DefaultHubName}")) .WithAutomaticReconnect() .Build(); // Register incoming handler _hubConnection.On("ReceiveMessage", (user, message) => { MessageReceived?.Invoke(user, message); }); await _hubConnection.StartAsync(); } public async Task SendMessageAsync(string user, string message) { if (_hubConnection.State == HubConnectionState.Connected) await _hubConnection.InvokeAsync("SendMessage", user, message); } public async ValueTask DisposeAsync() { if (_hubConnection is not null) { await _hubConnection.DisposeAsync(); } } } }