MediatR Notifications with Blazor (WASM) - Event handler does not update UI

2k views Asked by At

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();
}
1

There are 1 answers

1
Dmitry Pavlov On

The idea is your Blazor app should listen to MediatR command and update UI components once that happens. To do so you need to:

  1. Take care of the state management event to be triggered by MediatR handler.
  2. Make your Blazor component subscribe to this event and refresh UI using StateHasChanged - you can see the "State Container" example in 3 Ways to Communicate Between Components in Blazor article.