Extending SignalR Hubs
|
<< Click to Display Table of Contents >> Navigation: Web UI & API > Extending UI & API > Extending SignalR Hubs |
The DDK provides for mechanisms to define one’s own signalR hubs that are then discovered and bundled into the framework.
This can be done by the following:
dotnet add package Microsoft.AspNetCore.SignalR
To create a signalR hub simply implement the Hub class from Microsoft.AspNetCore.SignalR library.
using Microsoft.AspNetCore.SignalR;
namespace FrameworkTest
{
public class LiveUpdateHub : Hub
{
public async Task SendUpdate(string message)
{
await Clients.All.SendAsync("ReceiveUpdate", message);
}
}
}
The hub will be discovered at runtime and configured into the application’s life-cycle and be available for use.
The hub url will automatically be the same as the hub name.
To retrieve a hub from the framework, use the static GetHub<T> method on the static HubsLocator class.
This method should be called after successful initialization and completion of BncsFramework .
using BNCS.Core.DriverFramework;
using BNCS.Core.DriverFramework.SignalR;
using Microsoft.AspNetCore.SignalR;
internal class Program
{
private static IHubContext<LiveUpdateHub> hub;
static void Main(string[] args)
{
BncsFramework.Init();
//After succesful initialization of BncsFramework, retrieve the specific hub
hub = HubsLocator.GetHub<LiveUpdateHub>();
}
//Event occured that requires notifying the connected clients
private static void TestDriver_StatusChangedEvent(object? sender, string e)
{
//call methods on the hub to notify connected clients
hub!.Clients.All.SendAsync("broadcast message!", $"{e}");
}
}
Automatic hub discovery requires the hubs to be in the assembly configured at BncsFramework.Init ()
namespace FrameworkTest
{
BncsFramework.Init(...
//the hubs should be in a namespace within the assembly injected here
externalAssembly: typeof(Program).Assembly,
);
}
Automatic hub discovery requires classes to:
Inherit from Microsoft.AspNetCore.SignalR.Hub
Endpoint url naming convention: /hubname (same name as class name)