Author : MD TAREQ HASSAN

What is Hub?

Creating hub

Hubs/ChatHub.cs

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace SignalRChat.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

Hub class

Hub class properties

Hub connection events

Hubs/ChatHub.cs

public class ChatHub : Hub
{
	public override async Task OnConnectedAsync()
	{

		// ... ... ...
		
		await Clients.Caller.SendAsync("ReceiveMessage", "Start Message", DateTimeOffset.UtcNow);
		
		// ... ... ...
		
		await base.OnConnectedAsync();
	}

	public override async Task OnDisconnectedAsync(Exception exception)
	{
		// ... ... ...
		
		await base.OnDisconnectedAsync(exception);
	}
}

Dependency injection

Any service can be injected into hub by contructor inject in the same way of Controller or PageModel

Hubs/ChatHub.cs

public class ChatHub : Hub
{
	private IFoo _foo;

	public ChatHub(IFoo foo){
		_foo = foo
	}
	
	public async Task SendMessage(string user, string message)
	{
		await Clients.All.SendAsync("ReceiveMessage", user, message);
	}
}

Injecting hub into controller

[Route("[controller]")]
public class ChatController : Controller
{
	private readonly IHubContext<ChatHub> _chatHub;

	public ChatController(IHubContext<ChatHub> chatHub)
	{
		_chatHub = chatHub;
	}

	// ... ... ...
}