I have a standard Blazor SignalR chat. The main chat is working in a hub.class derived from Microsoft.AspNetCore.SignalR.Hub. This works fine.
Now I want to insert messages from outside the hub. For example answers from a chatbot with links in the text. When the user clicks one of the links in this text, a pre-defined message should be sent to the chat.
I tried first to update the messageInput-text-field from the chat with JS. This does not work because two-way-binding is not available from static JS functions.
Updating the text-field-value with Blazor via C# or sending directly a automated answer from a chatbot to the chat would be fine.
Unfortunately I was not able to get this working.
Has anybody a concise example of updating a Blazor SignalR from an outside-hub static methode via JS or C#?
Thank you very much in advance.
Daniel
You need to inject IHubContext<>
to access the hub externally.
This example shows how to inject the context into another service.
public class SomeService : ISomeService
{
private readonly IHubContext<ChatHub> chatHubContext;
private readonly System.Timers.Timer timer;
private int count;
public SomeService(IHubContext<ChatHub> chatHubContext)
{
this.chatHubContext = chatHubContext;
this.timer = new System.Timers.Timer(2000);
this.timer.Elapsed += Timer_Elapsed;
this.count = 0;
this.timer.Start();
}
private void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
this.count++;
Task.Run(() => this.chatHubContext.Clients.All.SendAsync(
"ReceiveMessage",
"SomeService",
$"Count: {this.count}"));
}
}
This is from a repo that I created. It has only 3 commits
NOTE: Although the service it a singleton it is not instanced until the FetchData page navigated to. IF you navigate to the FetchData page then back to the home page the calls to Signalr from the server will be seen.
This is a crude example I would not put a timer in a service like this normally.