How to fix 'The current thread is not associated with the renderer's synchronization context'?

I have just implemented a State Container like this and ran into the same error - but my service needs to be a singleton. So I found an example on the aspnetcore git that does exactly what the error message says to do. Call InvokeAsync -- not from your state container but when you try to change the state of your razor component.

https://github.com/dotnet/aspnetcore/blob/321db9d99f84cf7a67d453384292d9339de748d1/src/Components/test/testassets/BasicTestApp/DispatchingComponent.razor

So your state container doesn't need to change, just your component event handler does.

@code{
    protected override void OnInitialized()
    {
         _YourService.OnChange += OnMyChangeHandler;
    }

    public void Dispose()
    {
         _YourService.OnChange -= OnMyChangeHandler;
    }

    private async void OnMyChangeHandler(object sender, EventArgs e)
    {
        // InvokeAsync is inherited, it syncs the call back to the render thread
        await InvokeAsync(() => {
            DoStuff();
            StateHasChanged());
        }
    }
}

Now your service (if it's a singleton) can notify ALL your users at once! Think about all hoops we had to jump through in past to do this.


I posted this first thing in the morning thinking that I wouldn't have the time to look into and thinking that by time someone was able to help me out, I would have found the time to look into it more. Though I have spent a couple of days going back and forth on this already.

I finally found this article that explains that what I am trying to do is called a State Container.

What they said is that I could inject the class as a singleton, which is what I was doing or a scoped service. Turns out all I needed to do was change it to a scoped service and it works great!