Course contentsShow
← C#
Lesson 1361 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Integrating WebAssembly and SignalR

Maintain synchronized states in distributed systems using hybrid connectivity patterns.

In this lesson, you will learn how to bridge the gap between high-performance client-side logic in Blazor WebAssembly and real-time data synchronization using SignalR.

Bridging the Gap: Hybrid State Sync

When building a Blazor WebAssembly (WASM) application, your code executes entirely within the user's browser. While this provides a responsive experience, it creates a "silo" effect: if two users are looking at the same data, one user’s changes won’t appear on the other’s screen automatically. By integrating SignalR, we create a hybrid pattern where the WASM client acts as the interactive interface, and SignalR acts as the backbone for maintaining a synchronized state across all connected clients.

The Hybrid Connectivity Pattern

In this architecture, the SignalR Hub acts as the "source of truth" coordinator. Instead of the WASM client talking directly to a database for every update, it sends a command to the Hub. The Hub processes the logic and broadcasts the result to all connected clients.

Consider a shared dashboard scenario where multiple clients need to reflect the same count. Instead of polling the server, the WASM client listens for a specific event:

// In your Blazor Component
private HubConnection hubConnection;

protected override async Task OnInitializedAsync()
{
    hubConnection = new HubConnectionBuilder()
        .WithUrl(Navigation.ToAbsoluteUri("/statehub"))
        .Build();

    // Listen for state changes pushed from the server
    hubConnection.On<int>("ReceiveUpdate", (newCount) =>
    {
        currentCount = newCount;
        StateHasChanged(); // Notify Blazor to re-render
    });

    await hubConnection.StartAsync();
}

By combining this with the Flux/Redux pattern (Lesson 12), you can dispatch these SignalR-received updates directly into your state container. This ensures your WASM UI remains reactive to server-side events, effectively bridging the disconnected nature of client-side WASM with the distributed nature of real-time web communication.

Key Takeaway: Use SignalR to broadcast state transitions to all connected WebAssembly clients, ensuring that your local UI logic remains synchronized with the global system state in real-time.