Blazor WASM - Mediator Handle on different thread?

Viewed 28

Simple Blazor WASM Application. Using Mediator to trigger different validations on a registration form (Multiple Pages). Mediator is publishing the validation notification and the current or active form is then handling that notification and validating the form.

On Render the model and element reference are correctly initialized with a value. But once in the handler both the model and form (element reference) are null???

@implements INotificationHandler<ValidateRegistrationNotification>
@inject IRegistrationService RegService
@inject IMediator Mediator

<MudForm Model="@model" @ref="form" Validation="@(validator.ValidateValue)">
    
</MudForm>

@code {
    private MudForm? form { get; set; }
    private FormPersonalDetailModel? model { get; set; }
    private FormPersonalDetailValidator validator = new();

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            model = RegService.Registration.FormPersonalDetail;
            StateHasChanged();
        }
        return base.OnAfterRenderAsync(firstRender);
    }

    public async Task Handle(ValidateRegistrationNotification validate, CancellationToken cancellationToken)
    {
        if (validate.StageType == typeof(FormPersonalDetailModel))
        {
        await form!.Validate();

        if (form.IsValid)
        {
            RegService.GoToNextStage();
        }
    }
}

On After Render Async On After Render Variable Values

1

Handle

Mediator Handle Variable Values

2

1 Answers

This question has been asked on GitHub MediatR repository. Aaron Roberts gives a nice explanation in this answer:

Likely the problem here is that you are using a single class for both the razor backend and the notification handler. The .AddServices() extension method registers the handlers as Transient, which creates a new instance of the class to handle the notification. That means the one that is being used in rendering is not the same instance as the one that is handling the notification. In order to share data between the handlers and the Razor components you will need a shared dependency that both can interact with.

Related