Skip to content

Getting started

Installation

One package, one DI call per store, and one component wrapped around your router.

Packages

Reference Bit.Blex. It carries the runtime, the source generator that turns your [BlexStore] classes into reactive stores, and the Blazor integration (the Bit.Blex.Blazor namespace). The generator ships inside the package as an analyzer (under analyzers/dotnet/cs), so it adds nothing to your app's output - but NuGet does not flow analyzers to projects that only get a package transitively, so reference Bit.Blex directly from every project that declares stores. Every runtime package targets net10.0 and net11.0.

Add the packages
dotnet add package Bit.Blex

# .NET MAUI: XAML-bindable stores, the startup initializer, Preferences persistence
dotnet add package Bit.Blex.Maui

# optional, for unit tests
dotnet add package Bit.Blex.Testing

Or directly in the project file:

MyApp.csproj
<ItemGroup>
  <PackageReference Include="Bit.Blex" Version="11.0.0-pre-19" />
</ItemGroup>
Working inside this repository

The sample and docs projects live next to the sources, so they reference the generator as an analyzer project reference instead of consuming the published package: <ProjectReference Include="..\..\Bit.Blex.Generators\Bit.Blex.Generators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />.

Register the services

AddBitBlexServices registers the manager and the middleware pipeline; AddBitBlexStore<T> registers each store as a scoped service exposed both as its concrete type and as IBlexStore. A store is attached to the manager on first resolution, so its actions are observed even in hosts without a provider component - console apps, workers and tests included.

Program.cs
using Bit.Blex;
using Bit.Blex.Blazor;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");

builder.Services.AddBitBlexServices(options =>
{
    options.DevToolsName = "My App";
    options.UseMiddleware(ctx => Console.WriteLine($"[blex] {ctx.QualifiedName}"));
});

builder.Services.AddBitBlexStore<CounterStore>();
builder.Services.AddBitBlexStore<TodoStore>();

// Optional extras
builder.Services.AddBitBlexLocalStoragePersistence();
builder.Services.AddBitBlexHistory();

await builder.Build().RunAsync();

Registration APIs

Call Description
AddBitBlexServices(Action<BlexOptions>?, ServiceLifetime = Scoped) Registers BlexManager and the middleware pipeline. The options object configures the DevTools name, sanitizers, middleware, logging, the clock and the error sinks - every option is listed below.
AddBitBlexStore<TStore>(ServiceLifetime = Scoped) Registers a store, resolvable both as TStore and as IBlexStore. Constructor dependencies are injected, so a store can take an HttpClient like any other service. A scoped store is not registered here.
AddBitBlexPersistence(Action<BlexPersistenceOptions>?, ServiceLifetime = Scoped) Enables durable persistence for stores marked Persist = true. Requires an IBlexStorage registration. See Persistence.
AddBitBlexLocalStoragePersistence(…) Blazor: registers BlexBrowserStorage over window.localStorage and calls AddBitBlexPersistence.
AddBitBlexSessionStoragePersistence(…) Blazor: the same, over window.sessionStorage - cleared when the tab closes.
AddBitBlexQueries(Action<BlexQueryClientOptions>?, ServiceLifetime = Scoped) Registers BlexQueryClient, the server-state cache behind UseQuery and <BlexQueryView>. See Server state & queries.
AddBitBlexHistory(int maxEntries = 100, lifetime, filter?, groupBy?) Registers BlexHistory for in-app undo/redo. <BlexProvider> starts recording once rehydration completes. An overload takes a scope over the stores it covers. See Undo & redo.
AddBitBlexHistory<TStore>(int maxEntries = 100, lifetime, filter?, groupBy?) Registers BlexHistory<TStore>: an undo stack over one store type, beside or instead of the app-wide one.

Every call takes a lifetime, Scoped by default - one manager, one set of stores per Blazor Server circuit, per WebAssembly app, per test scope. Give them all the same one: a host with no scopes registers Singleton throughout, which is what the .NET MAUI builder extensions do for you.

BlexOptions - what AddBitBlexServices configures

Option Description
string DevToolsName The instance name in the Redux DevTools dropdown. Default "Blex". See DevTools.
RedactDevToolsKeys(params string[]) / DevToolsStateSanitizer / DevToolsActionSanitizer What the DevTools monitor is shown - redacted keys, a rewritten tree, rewritten action labels.
UseMiddleware<T>() / UseMiddleware(instance) / UseMiddleware(Action<BlexActionContext>) Middleware that observes every action, run in registration order. See Middleware.
UseFilter(predicate) / UseFilter(BlexAction<…>, predicate) Veto filters - for every action, or for one action by its typed descriptor.
UseLogging(LogLevel actionLevel = Debug) Every action, action failure and isolated failure to the host's ILogger. See Logging and tracing.
Action<BlexError>? OnError The sink for every failure Blex isolates from the pipeline. Without one they go to Console.Error. See Error isolation.
Action<BlexActionErrorContext>? OnActionError Hears every action body that throws - an effect's captured failure included. The exception still propagates.
TimeProvider? TimeProvider The clock for timestamps, debounces, retries and the query cache. Unset: one registered in the container, else the system clock. See Deterministic time.
bool ReportOffDispatcherChanges Report a store changed off the renderer's dispatcher (source "dispatcher"). Default true. See Threads and the dispatcher.
bool DetectInPlaceMutations Development aid: report an action that changed state without assigning a property (source "mutation"). Default false. See Change detection.

Hosting models

The store code is the same everywhere; what differs is which DI container registers Blex and where <BlexProvider> goes.

HostRegister Blex in, and what is worth knowing
Blazor Server
InteractiveServer
The server's Program.cs. Every circuit is a scope, so each user gets their own manager and stores. Browser storage is unreachable while prerendering; <BlexProvider> hydrates on the first interactive render instead. Leave EnableDevTools at its default (false) unless you want the state tree streamed over the circuit.
Blazor Web App
InteractiveWebAssembly, prerendered
Both Program.cs files, through one shared extension method. The server prerenders the same components the browser then runs, so both containers must resolve every store. Prerendered state is handed over through PersistentComponentState. This site is wired exactly this way.
Blazor Web App
InteractiveAuto
Both, as above. A first visit runs on the server, a later one in WebAssembly, and a store starts over when the runtime changes: mark what must survive the switch Persist = true.
Static server rendering The server's Program.cs. <BlexProvider> renders its content and the stores render their state; nothing that needs JS interop - browser storage, the DevTools bridge - is attempted, and nothing fails for want of it. Persistence and DevTools need the provider inside an interactive boundary.
Standalone Blazor WebAssembly Program.cs. One container, no prerendering - the samples above, as written.
.NET MAUI Blazor Hybrid MauiProgram.cs, scoped as in Blazor: the BlazorWebView creates the scope. No browser extension exists in a WebView, so leave EnableDevTools at its default (false). Persist to the WebView's localStorage or to OS-native Preferences. See .NET MAUI.
.NET MAUI
native XAML
MauiProgram.cs, through builder.UseBitBlex(). No scopes and no <BlexProvider>: the Bit.Blex.Maui builder extensions register singletons and do the provider's startup work at MauiApp.Build(). XAML binds to stores directly. See .NET MAUI.
Ask the MCP server for a working project

GetBlexSetupGuide returns the checklist and the real files of a working project for each of these hosts - server, wasm, auto, standalone-wasm, maui-hybrid and maui.

Add the provider

<BlexProvider> goes once, near the root of the app, wrapping the router. On initialization it registers every IBlexStore with the manager, restores prerendered and persisted state, and starts undo/redo recording; on first render it connects the Redux DevTools bridge.

App.razor
@using Microsoft.AspNetCore.Components.WebAssembly.Hosting
@inject IWebAssemblyHostEnvironment HostEnvironment

<BlexProvider EnableDevTools="@HostEnvironment.IsDevelopment()">
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <p>Not found.</p>
        </NotFound>
    </Router>
</BlexProvider>

<BlexProvider> parameters

Parameter Description
EnableDevTools bool, default false. Connects the Redux DevTools bridge on first render. Turn it on in development only.
PersistComponentState bool, default true. Hands prerendered store state to the interactive render through Blazor's PersistentComponentState, avoiding the prerender "double render" flicker. No effect when the framework service is unavailable.
ChildContent The application content rendered inside the provider.
Turn DevTools off in production

While enabled, the entire application state tree is serialized and handed to the Redux DevTools browser extension on every action. Bind EnableDevTools to your host environment so production builds never expose application state to an installed extension. See DevTools & time travel for redaction options.

Without Blazor

Stores, the manager and persistence never touch Blazor or JavaScript - only the Bit.Blex.Blazor namespace does. In a console app, worker or test, resolve the stores from DI (which registers them with the manager) and drive them directly. For persistence, implement IBlexStorage over a file or database and call AddBitBlexPersistence().

Headless host
var services = new ServiceCollection();
services.AddBitBlexServices();
services.AddBitBlexStore<CounterStore>();

var provider = services.BuildServiceProvider();

// Resolving the store registers it with the manager.
var store = provider.GetRequiredService<CounterStore>();
var manager = provider.GetRequiredService<BlexManager>();

store.Increment();
Console.WriteLine(manager.CaptureGlobalState().ToJsonString());
// {"counter":{"Count":1,"Step":1}}

Trimming and AOT

Snapshots - SerializeState, persistence, the DevTools payload - go through System.Text.Json. By default that is the reflection-based serializer, whose metadata a trimmed publish (the Blazor WebAssembly release default) is free to strip for types it cannot see being used. Point the shared options at a source-generated context and every generated snapshot uses it instead.

Program.cs
[JsonSerializable(typeof(CartLine))]
[JsonSerializable(typeof(BlexEntityState<Todo, int>))]
internal partial class AppJsonContext : JsonSerializerContext;

// Before any store is resolved or snapshotted -- the options instance becomes
// read-only on first use, so this belongs in startup.
BlexJson.Configure(o => o.TypeInfoResolver = AppJsonContext.Default);
Register the state types, not the stores

A store class is never serialized - only the value of each [BlexState] field, one property at a time. So the context needs CartLine and BlexEntityState<Todo, int>, not CartStore. A store whose state is all primitives and strings needs nothing at all.

Requirements

  • .NET 10 or 11 for Bit.Blex, Bit.Blex.Maui and Bit.Blex.Testing - each ships net10.0 and net11.0 builds.
  • netstandard2.0 for the generator, as Roslyn analyzers require.
  • Nullable reference types are supported and expected; generated code is annotated.
An unhandled error has occurred. Reload 🗙