For a server-side Blazor project I created a little class that gathers popup messages (toasts) in an array and emits events when this list changes so a component can listen to it and displays the messages.
In an other project this works fine but in my latest project somehow this service leaks to other users so everybody is getting the same popup messages. It looks like the scoped service becomes a singleton.
The service code:
public class PopupMessageService
{
public static event Action<List<PopupMessage>>? OnChange;
private readonly List<PopupMessage> _messages = new List<PopupMessage>();
public void ShowMessage(PopupMessage message)
{
_messages.Add(message);
var timer = new Timer(3000);
timer.Elapsed += RemoveFirst;
timer.AutoReset = false;
timer.Start();
OnChange?.Invoke(_messages);
}
private void RemoveFirst(object source, ElapsedEventArgs args)
{
if (_messages.Count == 0)
{
return;
}
_messages.RemoveAt(0);
OnChange?.Invoke(_messages);
}
}
In Startup.cs
:
services.AddScoped<PopupMessageService>();
Usage inside a component:
@inject PopupMessageService PopupMessageService
PopupMessageService.ShowMessage(new ViewServices.PopupMessage
{
Message = "Changes saved!",
MessageType = ViewServices.PopupMessage.Type.Success
});
Inside a component that is showing the messages:
protected override void OnInitialized()
{
PopupMessageService.OnChange += HandleMessagesChanged;
}
So my question is: how can I debug why the PopupMessageService.OnChange
is picked up by every connected user? Or maybe someone can spot problems with the code?