- Add the new folder Hubs to Question.Web
- Add new class QuestionsHub to folder Hub
- Set the base class of the QuestionsHub class to Hub
Add a static class with an extension method for the refresh command
public static class QuestionsHubExtensions
{
public static async Task SendRefreshAsync(this IHubContext<QuestionsHub>? hub)
{
if (hub != null)
await hub.Clients.All.SendAsync("refresh");
}
}
ConfigureServices
// Configuration for SignalR
builder.Services.AddSignalR();
Configure (after Maps)
// Activate SignalR Hub
app.MapHub<QuestionsHub>("/hub");
Add a IHubContext as parameter to the constructor for dependency injection
private readonly IHubContext<QuestionsHub>? _hub;
public AskQuestionCommand(QuestionsContext context, IHubContext<QuestionsHub>? hub)
{
_context = context;
_hub = hub;
}
Call the refresh SendRefreshAsync in the handle method after the save
await _hub.SendRefreshAsync();
Add a IHubContext as parameter to the constructor for dependency injection
private readonly IHubContext<QuestionsHub>? _hub;
public VoteForQuestionCommand(QuestionsContext context, IHubContext<QuestionsHub>? hub)
{
_context = context;
_hub = hub;
}
Call the refresh SendRefreshAsync in the handle method after the save
await _hub.SendRefreshAsync();
Modify the initialisation of the RequestHandlers
private GetQuestionsQuery GetQuestionsQueryHandler => new(_context);
private AskQuestionCommand AskQuestionCommandHandler => new(_context, null);
private VoteForQuestionCommand VoteForQuestionCommandHandler => new(_context, null);
Add SignalR script import
<script src="https://cdn.jsdelivr.net/npm/@microsoft/[email protected]/dist/browser/signalr.min.js" integrity="sha256-zvQeaEXmmM78llGmEtKvwp5dG1kF3iJ3GhdjrO4b+fg=" crossorigin="anonymous"></script>
<title>Ask your questions</title>
Remove the call of getQuestions from the methods ask and vote
Add connection to hub and register to the refresh message to call getQuestions
// app.mount("#questionView");
const vm = app.mount("#questionView");
const connection = new signalR.HubConnectionBuilder()
.withUrl("hub")
.build();
connection.start().catch(err => console.error(err.toString()));
connection.on("Refresh", () => { console.log("Refresh"); vm.getQuestions(); });