I have a BackgroundWorker which is supposed to broadcast something to all online clients in 5 seconds interval:
DeactivationBackgroundWorker:
public class DeactivationBackgroundWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
{
private readonly IRepository<HitchRequest, long> _hitchRequestRepository;
private readonly IHitchHub _hitchHub;
public DeactivationBackgroundWorker(AbpTimer timer,
IRepository<HitchRequest, long> hitchRequestRepository,
IHitchHub hitchHub) : base(timer)
{
_hitchRequestRepository = hitchRequestRepository;
Timer.Period = 5000;
_hitchHub = hitchHub;
}
protected override async void DoWork()
{
await broadcastHitchRequestsAsync();
}
[UnitOfWork]
private async Task broadcastHitchRequestsAsync() {
var activeHitchRequests = _hitchRequestRepository.GetAllList(p => p.IsActive);
foreach (var hitchRequest in activeHitchRequests)
{
await _hitchHub.RequestHitch(hitchRequest.Id);
}
}
}
IHitchHub:
public interface IHitchHub: ITransientDependency
{
Task RequestHitch(long hitchId);
}
HitchHub:
public class HitchHub : AbpCommonHub, IHitchHub
{
private readonly IOnlineClientManager _onlineClientManager;
public HitchHub(IOnlineClientManager onlineClientManager, IClientInfoProvider clientInfoProvider): base(onlineClientManager, clientInfoProvider)
{
_onlineClientManager = onlineClientManager;
}
public async Task RequestHitch(long hitchId)
{
var onlineClients = _onlineClientManager.GetAllClients();
foreach (var onlineClient in onlineClients) {
var signalRClient = Clients.Client(onlineClient.ConnectionId);
await signalRClient.SendAsync("receiveHitch", hitchId);
}
}
}
I do not know why the Clients in the HitchHub class is always null! Where should I initialize it?
If your using Asp.net Core see:
Call SignalR Core Hub method from Controller
Otherwise:
Hub's shouldn't be instantiated by yourself or any injection framework
You have to use the ConnectionManager. For your code you should use:
**Background information about Hub object lifetime: **
https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-server:
See also: https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-server#callfromoutsidehub
Inject
IHubContext<HitchHub>
instead ofIHitchHub
.For example, see ABP's SignalRRealTimeNotifier.
Related issue: https://github.com/aspnet/SignalR/issues/182