SignalR: Setting up a Hub to handle server events

By | June 6, 2014

This is a simple how to (code provided), on quickly setting up a SignalR Hub to broadcast server raised events to clients

Prerequisite

  • SignalR is already setup in your Asp.Net Mvc application
  • You know how to call client methods
  • You already know how to write and wire up events

Lets get to it

1. Create your Hub and name your Hub (i.e. StatusReporterHub)

public class StatusReporterHub : Hub
{
    
}

2. Make sure the following usings are added

using System;
using System.Linq;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

3. Create a new sealed class, relate the name to your Hub (i.e. StatusReporterBroadcaster). Use the sealed modifier to prevent other classes from inheriting from it. The class needs to use the singleton pattern as the class should only be initialized once. We use Lazy to make it thread safe.

public sealed class StatusReporterBroadcaster
{
    private readonly static Lazy<StatusReporterBroadcaster> instance =
        new Lazy<StatusReporterBroadcaster>(() => new StatusReporterBroadcaster(GlobalHost.ConnectionManager.GetHubContext<StatusReporterHub>().Clients));
 
    private IHubConnectionContext clients { getset; }
 
 
    public static StatusReporterBroadcaster Instance
    {
        get
        {
            return instance.Value;
        }
    }
 
    private StatusReporterBroadcaster(IHubConnectionContext _clients)
    {
        clients = _clients;
 
        //Hook up events here 
        //
        //Example: using a static event
        //TaskRepository.TaskStatusChanged += (changeType, dto) =>
        //{
        //    Clients.All.TaskStatusChanged(changeType.ToString("F"), dto);
        //};
    }
}

3.  Now in your Hub class add below code so your Hub looks like this:

public class StatusReporterHub : Hub
{
    private readonly StatusReporterBroadcaster broadcaster;
 
    public StatusReporterHub(): this(StatusReporterBroadcaster.Instance)
    {
    }
 
    public StatusReporterHub(StatusReporterBroadcaster _broadcaster)
    {
        broadcaster = _broadcaster;
    }
 
}

5. And that is it, all done.

 


											

Leave a Reply

Your email address will not be published. Required fields are marked *