Skip to content

Blazor Services

This document covers the core services that power Fusion's Blazor integration: CircuitHub, JSRuntimeInfo, RenderModeHelper, and RenderModeDef.

See also: UICommander and UIActionTracker – command execution and responsive UI updates. Both are optional and can be replaced with custom abstractions.

CircuitHub

View Source

CircuitHub is a scoped service that acts as the central hub for accessing Fusion and Blazor services within a circuit. It caches frequently used services and provides information about the current render mode.

Purpose

  • Caches commonly used services for efficient access
  • Provides render mode information (prerendering vs interactive)
  • Exposes the Blazor Dispatcher for thread-safe UI updates
  • Serves as the primary access point for Fusion services in Blazor components

Key Properties

PropertyTypeDescription
IdlongUnique identifier for this circuit hub instance
ServicesIServiceProviderThe service provider
StateFactoryStateFactoryFactory for creating states
UICommanderUICommanderCommander for executing UI commands
CommanderICommanderThe underlying commander
SessionSessionCurrent user session (lazy-resolved)
SessionResolverISessionResolverSession resolver service
NavNavigationManagerBlazor's navigation manager
JSIJSRuntimeJavaScript runtime instance
JSRuntimeInfoJSRuntimeInfoInformation about the JS runtime
IsPrerenderingboolTrue if currently prerendering
IsInteractiveboolTrue if circuit is interactive
DispatcherDispatcherBlazor dispatcher for UI thread
RenderModeRenderModeDefCurrent render mode definition
WhenInitializedTaskCompletes when CircuitHub is initialized

Initialization

CircuitHub must be initialized with a dispatcher and render mode. This typically happens automatically in CircuitHubComponentBase:

csharp
CircuitHub.Initialize(this.GetDispatcher(), renderMode);

Usage in Components

Components that inherit from CircuitHubComponentBase get direct access to CircuitHub:

razor
@inherits CircuitHubComponentBase

@code {
    protected override void OnInitialized()
    {
        // Access services through CircuitHub
        var session = CircuitHub.Session;
        var commander = CircuitHub.Commander;

        // Check render mode
        if (CircuitHub.IsPrerendering) {
            // Skip expensive operations during prerender
        }
    }
}

JSRuntimeInfo

View Source

JSRuntimeInfo provides information about the JavaScript runtime and the current execution context. It helps detect whether the app is in prerendering mode or interactive mode.

Purpose

  • Detects if running in server-side prerendering or interactive mode
  • Identifies the type of JS runtime (Remote, WASM, etc.)
  • Useful for conditional logic based on execution context

Key Properties

PropertyTypeDescription
RuntimeIJSRuntime?The underlying JavaScript runtime (null if unavailable)
IsRemoteboolTrue if using RemoteJSRuntime (server-side)
ClientProxyobject?The SignalR client proxy (server-side only)
IsPrerenderingboolTrue if in server-side prerendering (IsRemote && ClientProxy is null)
IsInteractiveboolTrue if runtime is available and not prerendering

How It Works

JSRuntimeInfo uses reflection to inspect the runtime type and detect the execution context:

  • Prerendering: IsRemote is true but ClientProxy is null (no client connection yet)
  • Interactive Server: IsRemote is true and ClientProxy is not null
  • WebAssembly: Runtime is the WASM JS runtime (IsRemote is false)

Usage Example

csharp
var jsInfo = services.GetRequiredService<JSRuntimeInfo>();

if (jsInfo.IsPrerendering) {
    // Return placeholder data during prerender
    return DefaultData;
}

if (jsInfo.IsInteractive) {
    // Safe to make JS interop calls
    await JS.InvokeVoidAsync("someFunction");
}

RenderModeDef

View Source

RenderModeDef defines a rendering mode configuration. It supports both pre-.NET 8 and .NET 8+ render mode definitions.

Purpose

  • Encapsulates render mode configuration
  • Provides a unified API across different .NET versions
  • Enables runtime render mode switching

Key Properties

PropertyTypeDescription
KeystringShort identifier ("a", "s", "w")
TitlestringHuman-readable name
ModeIComponentRenderMode(.NET 8+) The Blazor render mode
IsWebAssemblybool(Pre-.NET 8) Whether this is WASM mode
Prerenderbool(Pre-.NET 8) Whether prerendering is enabled

Built-in Modes

KeyTitleMode
"a"AutoInteractiveAutoRenderMode(prerender: true)
"s"ServerInteractiveServerRenderMode(prerender: true)
"w"WASMInteractiveWebAssemblyRenderMode(prerender: true)

Static Members

csharp
// All available render modes (can be customized)
RenderModeDef[] All { get; set; }

// Dictionary lookup by key
IReadOnlyDictionary<string, RenderModeDef> ByKey { get; }

// Default render mode (first in All array)
RenderModeDef Default { get; }

// Get mode by key, or default if not found
RenderModeDef GetOrDefault(string? key)

Usage in Host Page

razor
@* _HostPage.razor *@
@{
    var renderMode = RenderModeDef.GetOrDefault(RenderModeKey);
}

<App @rendermode="renderMode.Mode" />

RenderModeHelper

View Source

RenderModeHelper provides utilities for managing and switching between different render modes at runtime.

Purpose

  • Displays the current render mode
  • Enables switching between Server and WebAssembly modes
  • Constructs mode-switch URLs

Key Properties and Methods

MemberTypeDescription
CurrentModeRenderModeDef?Current render mode (null if not initialized)
GetCurrentModeTitle()stringHuman-readable title for current mode
ChangeMode(RenderModeDef)voidInitiates a render mode change
GetModeChangeUrl(...)stringConstructs the URL for switching modes

Render Mode Switch URL Format

/fusion/renderMode/{key}?redirectTo={url}

For example: /fusion/renderMode/w?redirectTo=/dashboard

Usage Example

razor
@inject RenderModeHelper RenderModeHelper

<div class="render-mode-selector">
    <span>Current: @RenderModeHelper.GetCurrentModeTitle()</span>

    @foreach (var mode in RenderModeDef.All) {
        <button @onclick="() => RenderModeHelper.ChangeMode(mode)">
            @mode.Title
        </button>
    }
</div>

Server Configuration

To enable render mode switching, map the endpoint in your server:

csharp
app.MapFusionRenderModeEndpoints(); // Maps /fusion/renderMode/{key}

IHasCircuitHub Interface

View Source

A marker interface for types that have access to a CircuitHub instance.

csharp
public interface IHasCircuitHub : IHasServices
{
    CircuitHub CircuitHub { get; }
}

This interface is implemented by CircuitHubComponentBase and all components deriving from it. It enables service resolution patterns and dependency injection scenarios.

DI Registration

All services are registered when you call AddBlazor():

csharp
services.AddFusion().AddBlazor();

This registers:

ServiceLifetimeDescription
CircuitHubScopedCentral service hub
JSRuntimeInfoScoped/SingletonJS runtime information
RenderModeHelperScopedRender mode utilities
UICommanderScopedCommand execution for UI (see UICommander)
UIActionTrackerScopedTracks UI actions (see UICommander)
UIActionFailureTrackerScopedTracks failed UI actions