从 ABP 中的 BackgroundWorker 调用 SignalR 服务 [英] Calling SignalR service from a BackgroundWorker in ABP

查看:15
本文介绍了从 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 总是为 null!我应该在哪里初始化它?

I do not know why the Clients in the HitchHub class is always null! Where should I initialize it?

推荐答案

Inject IHubContext 而不是 IHitchHub.

Inject IHubContext<HitchHub> instead of IHitchHub.

例如,请参见 ABP 的 SignalRRealTimeNotifier.

For example, see ABP's SignalRRealTimeNotifier.

相关问题:https://github.com/aspnet/SignalR/issues/182

这篇关于从 ABP 中的 BackgroundWorker 调用 SignalR 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆