4

In my Asp.Net Core application I receive updates from a .Net Client through SignalR Core. With these updates, I try to know the status of a background service that is running on the .Net client. Some examples:

  • "Timer has been started successfully."

  • "Timer has been paused successfully."

  • "Timer has been resumed successfully."

  • "Timer could not be started."

I want to use these messages in my Asp.Net Core application and transfer them to the upper layer of my project (Logic layer) by sending events from the Hub (Data access layer). I can't seem to figure out how to do this and I don't find any documentation regarding this problem.

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");
    }
}

In the code example above you can see what I'm trying to accomplish. The problem I'm having is that the event is not accessible in classes outside the hub so I cannot use it.

Sam
  • 81
  • 2
  • 12
  • Whats wrong doing the same directly from the background service without using SignalR? – TanvirArjel Mar 18 '19 at 12:41
  • The timer will be running for 4 hours on the Azure Cloud. I read that it's possible that background services can automatically stopped after a while so I'm trying to write a WebJob that can run on it's own in an Azure App Service. – Sam Mar 18 '19 at 12:45

1 Answers1

2

Change your TimerCouldNotBeStarted event to be a service that you put in DI. Then resolve the service in your Hubs constructor and use it in your methods.

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);
    }
}
Brennan
  • 1,834
  • 1
  • 7
  • 13