using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data; using AsbCloudApp.Repositories; using AsbCloudApp.Services.Notifications; using AsbCloudWebApi.SignalR.ConnectionManager; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; namespace AsbCloudWebApi.SignalR.Services; public class SignalRNotificationTransportService : INotificationTransportService { private readonly IConnectionManager connectionManager; private readonly IHubContext notificationHubContext; private readonly IServiceProvider serviceProvider; public SignalRNotificationTransportService(IConnectionManager connectionManager, IHubContext notificationHubContext, IServiceProvider serviceProvider) { this.connectionManager = connectionManager; this.notificationHubContext = notificationHubContext; this.serviceProvider = serviceProvider; } public int IdTransportType => 0; public async Task SendAsync(NotificationDto notification, CancellationToken cancellationToken) { const string method = "notifications"; var connectionId = connectionManager.GetConnectionIdByUserId(notification.IdUser); if (!string.IsNullOrWhiteSpace(connectionId)) { notification.SentDate = DateTime.UtcNow; await notificationHubContext.Clients.Client(connectionId) .SendAsync(method, notification, cancellationToken); var scope = serviceProvider.CreateScope(); var notificationRepository = scope.ServiceProvider.GetService(); if (notificationRepository != null) { await notificationRepository.UpdateAsync(notification, cancellationToken); } } } public async Task SendRangeAsync(IEnumerable notifications, CancellationToken cancellationToken) { foreach (var notification in notifications) { await SendAsync(notification, cancellationToken); } } }