本文介绍了从ABP中的BackgroundWorker调用SignalR服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个BackgroundWorker,它应该在5秒的间隔内向所有在线客户端广播一些内容:
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);
}
}
}
我不知道为什么HitchHub类中的 Clients 总是为空!我应该在哪里初始化它?
I do not know why the Clients in the HitchHub class is always null! Where should I initialize it?
推荐答案
注入IHubContext<HitchHub>
而不是IHitchHub
.
例如,请参阅ABP的.
For example, see ABP's SignalRRealTimeNotifier.
相关问题: https://github.com/aspnet/SignalR/issues/182
这篇关于从ABP中的BackgroundWorker调用SignalR服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!