Toast is shown to everyone using app

My Blazor server app shows other user's toast message. Is there any way to show the message only to the user who triggeres the event? I added the toast component in the MainLayout.razor

<main id="main">
    <div class="p-3">
        <ErrorBoundary>
            <ChildContent>
                <CascadingValue Value="@offset" IsFixed="true">
                    @Body
                </CascadingValue>
            </ChildContent>
            <ErrorContent Context="exception">
                <div class="alert alert-danger" role="alert">
                    <p>An unexpected error has occurred: @exception.Message</p>
                    <p>Please refresh the page by pressing F5 or try again later.</p>
                </div>
            </ErrorContent>
        </ErrorBoundary>
        <SfToast @ref="_toast" Target="#main">
            <ToastPosition X="Right" Y="Bottom"></ToastPosition>
        </SfToast>
    </div>
</main>
@code {
private SfToast? _toast;
protected override async Task OnInitializedAsync()
  {
      AlertService.OnAlertMessageChanged += AlertMessageAsync;

  }

    private async void AlertMessageAsync(object sender, AlertEventArgs e)
    {
        var cssClass = e.Type switch
        {
            AlertTypes.Error => "e-toast-danger",
            AlertTypes.Warning => "e-toast-error",
            AlertTypes.Information => "e-toast-info",
            AlertTypes.Success => "e-toast-success",
        };


        var iconCss = e.Type switch
        {
            AlertTypes.Error => "e-circle-close",
            AlertTypes.Warning => "e-warning",
            AlertTypes.Information => "e-circle-info",
            AlertTypes.Success => "e-circle-check",
        };


        await _toast.ShowAsync(new ToastModel
            {
                Title = e.Title,
                Content = e.Message,
                CssClass = cssClass,
                Icon = iconCss,
                ShowCloseButton = true,
                ShowProgressBar = true,
                Timeout = e.Seconds * 1000
            });
    }
...
}

And uses a service to trigger the toast.

public class AlertService
{
    public event EventHandler<AlertEventArgs>? OnAlertMessageChanged;

    public void ShowAlert(string title, AlertTypes type, string message, int seconds = 20)
        => OnAlertMessageChanged?.Invoke(this, new AlertEventArgs(title, type, message, seconds));
}

public class AlertEventArgs(string title, AlertTypes type, string message, int seconds)
{
    public string Title { get; set; } = title;
    public AlertTypes Type { get; set; } = type;
    public string Message { get; set; } = message;
    public int Seconds { get; set; } = seconds;
}

1 Reply

PK Priyanka Karthikeyan Syncfusion Team February 18, 2025 12:44 PM UTC

Hi Yongkee Cho,

In a Blazor Server application, all users share the same server instance. As a result, when a service is registered as a singleton, it is shared across all users. This means that any event, such as OnAlertMessageChanged, will be triggered globally, causing the toast message to be visible to all connected users instead of being limited to the user who initiated the action.

To ensure that each user (Blazor circuit) has an isolated instance of AlertService, we recommend changing its registration in Program.cs from singleton to scoped:

Update your service registration as follows:

// Previous (causes global toast messages for all users) builder.Services.AddSingleton<AlertService>(); // Recommended (ensures each user gets a separate instance) builder.Services.AddScoped<AlertService>();

By using scoped services, each user session maintains its own instance of AlertService, preventing messages from being inadvertently shared across different users.

Additionally, if our understanding of your scenario is not entirely accurate, we would greatly appreciate it if you could provide further details about your specific requirements. This will help us better align our response with your expectations and ensure we provide you with the most effective solution.


Regards,

Priyanka K


Attachment: ShoworhidetoastusingserviceinBlazormain_c726de4.zip

Loader.
Up arrow icon