2

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?

Thomas Huijzer
  • 354
  • 1
  • 7
  • 1
    What do you think might be interesting about a `static` event (vs a non-`static` one)? – mjwills Apr 20 '20 at 09:25
  • 1
    @mjwills Ah! Yes, thank you. I now see that I got a `Cannot access non-static event 'OnChange' in static context` message and without giving it much thought I allowed the IDE to change the event to static. – Thomas Huijzer Apr 20 '20 at 09:36

0 Answers0