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

Event Bus Architectures

Implement a global event bus to handle cross-component communication for modular apps.

In this lesson, you will learn how to implement a lightweight Event Bus to enable decoupled, cross-component communication in your Blazor applications.

Why an Event Bus?

In modular Blazor apps, components are often deeply nested or exist in entirely different parts of the render tree. Using EventCallback chains to pass data through multiple layers of "parent-child-grandchild" components leads to "prop-drilling," which makes your code brittle and hard to maintain. An Event Bus acts as a central mediator, allowing any component to publish an event and any other component to subscribe to it without knowing about each other’s existence.

The Implementation

To implement this, we create a singleton service that acts as the message broker.

public class EventBus
{
    public event Action<string, object>? OnMessageReceived;

    public void Publish(string topic, object data) 
        => OnMessageReceived?.Invoke(topic, data);
}

Register this as a singleton in your Program.cs: builder.Services.AddSingleton<EventBus>();

Using the Bus

Now, any component can inject the EventBus and listen for specific events. Because this is a long-lived service, we must handle the lifecycle carefully.

@implements IDisposable
@inject EventBus Bus

protected override void OnInitialized()
{
    Bus.OnMessageReceived += HandleEvent;
}

private void HandleEvent(string topic, object data)
{
    if (topic == "UserLoggedIn") { /* Update UI */ }
}

public void Dispose() => Bus.OnMessageReceived -= HandleEvent;

When a user logs in, a separate component simply calls Bus.Publish("UserLoggedIn", userProfile);. The listening component reacts immediately, even if it is currently hidden in a completely different layout area.

By using an Event Bus, you decouple your business logic from your UI hierarchy, which is essential for maintaining large-scale Blazor architectures where components should not be tightly coupled to their neighbors. Always remember to unsubscribe in Dispose() to prevent memory leaks, as the singleton service will outlive your component instances.

Key Takeaway: An Event Bus decouples your components by centralizing event distribution, replacing complex parent-child callback chains with a simple, scalable publish-subscribe pattern.