I'm trying to hook up MediatR in a client-side Blazor application purely to handle event notifications between components.
The event is published, and it gets picked up by a separate component with a handler, but I can't update the UI from the handler.
I believe the reason is the handler invoked by MediatR is not the same instance as the one used by the UI component. If that makes sense?
Has anyone used MediatR notifications in Blazor?
Publish component:
@inject MediatR.IMediator _mediator
<h3>Sender</h3>
<button @onclick="SendNotification">Send notification</button>
@code {
private void SendNotification()
{
_mediator.Publish(new MyNotification { Message = "Hello World!" });
}
}
Subscribe component:
@using MediatR;
@implements INotificationHandler<MyNotification>;
<h3>Receiver</h3>
<p>Message: @Message</p>
@code {
private string Message { get; set; } = "[No message]";
public Task Handle(MyNotification notification, System.Threading.CancellationToken cancellationToken)
{
Message = notification.Message; // <-- THIS DOES NOT UPDATE THE UI
return Task.CompletedTask;
}
}
Notification:
public class MyNotification : INotification
{
public string Message { get; set; }
}
Main:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddMediatR(typeof(Program));
await builder.Build().RunAsync();
}
The idea is your
Blazor
app should listen toMediatR
command and updateUI
components once that happens. To do so you need to:MediatR
handler.Blazor
component subscribe to this event and refresh UI usingStateHasChanged
- you can see the "State Container" example in 3 Ways to Communicate Between Components in Blazor article.