I have Asp.Net Core 6 Web Admin Api.
I have have a table with entities and an enpoint to add a new entity.
I want when one user creates a new entity - the others to see this in real time. That is why I am adding SignalR
.
I want to signal to the clients to update AFTER the entity has been saved successfully to the database.
What is the best way to do it?
I see here that there is IHubContext<NotificationHub>
.
I believe in my scenario the best way would be to inject the context in the Controller and call it in the action AFTER the entity is saved to the DB?
Is there a better solution to the problem?
[ApiController]
public class ItemsController : ControllerBase
{
private readonly IHubContext<NotificationHub> _hubContext;
private readonly IRepository<Item> _repo;
public ItemsController (IHubContext<NotificationHub> hubContext, IRepository<Item> repo)
{
_hubContext = hubContext;
_repo = repo;
}
[HttpPost]
public async Task<IActionResult> AddItem(ItemDto item)
{
var id = await _repo.AddAsync(item);
if (id is null)
{
return BadRequest();
}
await _hubContext.Clients.All.SendAsync("NotificationReceived", id);
return Created(item.Id);
}
According to the documentation this is the right way - inject IHubContext<> where we need it. I failed to see this page at first.
Maybe the best option is to use a strongly-typed HubContext to avoid errors with string names.
public class ChatController : Controller
{
private IHubContext<ChatHub, IChatClient> _strongChatHubContext { get; }
public ChatController(IHubContext<ChatHub, IChatClient> chatHubContext)
{
_strongChatHubContext = chatHubContext;
}
public async Task SendMessage(string user, string message)
{
await _strongChatHubContext.Clients.All.ReceiveMessage(user, message);
}
}