有没有办法在SignalR Core Hub中实现事件?

问题描述 投票:1回答:1

在我的Asp.Net Core应用程序中,我通过SignalR Core从.Net客户端接收更新。通过这些更新,我尝试了解.Net客户端上运行的后台服务的状态。一些例子:

  • “计时器已成功启动。”
  • “计时器已成功暂停。”
  • “计时器已成功恢复。”
  • “计时器无法启动。”

我想在我的Asp.Net Core应用程序中使用这些消息,并通过从Hub(数据访问层)发送事件将它们传输到我的项目的上层(逻辑层)。我似乎无法弄清楚如何做到这一点,我没有找到任何关于这个问题的文档。

public class TimerHub : Hub
{
    public event EventHandler TimerCouldNotBeStarted;

    // Method called by .Net Client
    Task TimerStatusUpdate(string message)
    {
        switch (message)
        {
            case "Timer could not be started.":
                OnTimerCouldNotBeStarted(EventArgs.Empty); // Raise event
                break;
        }

        return Clients.All.SendAsync("EditionStatusUpdate", message);
    }

    protected virtual void OnTimerCouldNotBeStarted(EventArgs e)
    {
        TimerCouldNotBeStarted?.Invoke(this, e);
    }
}

public class EditionEngine
{
    private readonly IHubContext<TimerHub> _timerHubContext;

    public EditionEngine(IHubContext<TimerHub> hubContext)
    {
        _timerHubContext = hubContext;

        _timerHubContext.TimerCouldNotBeStarted += TimerNotStarted; // Event is not found in the TimerHub
    }

    private static void TimerNotStarted(object sender, EventArgs e)
    {
        Console.WriteLine("Event was raised by Hub");
    }
}

在上面的代码示例中,您可以看到我正在尝试完成的任务。我遇到的问题是,在集线器外的类中无法访问该事件,因此我无法使用它。

asp.net-core signalr.client asp.net-core-signalr
1个回答
0
投票

将您的TimerCouldNotBeStarted事件更改为您在DI中提供的服务。然后解决Hubs构造函数中的服务并在方法中使用它。

public class TimerHub : Hub
{
    private readonly TimeService _timer;

    public TimerHub(TimerService timer)
    {
        _timer = timer;
    }

    Task TimerStatusUpdate(string message)
    {
        switch (message)
        {
            case "Timer could not be started.":
                _timer.OnTimerCouldNotBeStarted(EventArgs.Empty); // Raise event
                break;
        }

        return Clients.All.SendAsync("EditionStatusUpdate", message);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.