Код: Выделить всё
public class SystemStateClientService : IAsyncDisposable
{
private readonly HubConnection _hubConnection;
private bool _started = false;
private CurrentSystemState? _currentState = null;
public event Action? OnStateChanged;
public SystemStateClientService(NavigationManager navigation)
{
_hubConnection = new HubConnectionBuilder()
.WithUrl(navigation.ToAbsoluteUri("/hubs/notification"))
.WithAutomaticReconnect()
.Build();
}
public async Task StartAsync()
{
if (_started)
return;
_hubConnection.On("SystemStateChanged", (newState) =>
{
if (Enum.TryParse(newState, out CurrentSystemState parsed))
{
_currentState = parsed;
OnStateChanged?.Invoke(parsed);
}
});
try
{
if (_hubConnection.State == HubConnectionState.Disconnected)
{
await _hubConnection.StartAsync();
Console.WriteLine("✅ SignalR connection started.");
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Failed to start SignalR connection: {ex.Message}");
}
_started = true;
}
public async Task GetCurrentStateAsync()
{
if (_currentState != null)
return _currentState;
try
{
var currentStateStr = await _hubConnection.InvokeAsync("GetCurrentSystemState");
if (Enum.TryParse(currentStateStr, out CurrentSystemState parsed))
{
_currentState = parsed;
OnStateChanged?.Invoke(parsed);
return parsed;
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Failed to fetch current system state from server: {ex.Message}");
}
return null;
}
public async ValueTask DisposeAsync()
{
await _hubConnection.DisposeAsync();
}
}
< /code>
В идеале я хотел бы пометить это как Singleton, но, поскольку он использует концентратор SignalR, он позволит только впрыскивать. Итак, в моей программе.builder.Services.AddScoped();
Код: Выделить всё
@inherits LayoutComponentBase
@inject SystemStateClientService SystemStateClient
[url=.]Reload[/url]
🗙
@code {
private bool _initialized = false;
protected override async Task OnInitializedAsync()
{
if (!_initialized)
{
await SystemStateClient.StartAsync();
_initialized = true;
}
}
}
< /code>
Я просто использую < /p>
@inject SystemStateClientService SystemStateClient
Кто -нибудь может помочь здесь? Или у вас есть другие идеи для решения?
Подробнее здесь: https://stackoverflow.com/questions/796 ... ignalr-hub
Мобильная версия