Getting started
.NET MAUI
A Blazor Hybrid app uses Blex exactly as any Blazor app does. A native XAML app binds straight to the stores - Bit.Blex.Maui registers them for an app without DI scopes, and does at startup what <BlexProvider> does in Blazor.
Two ways to build with MAUI
Every runtime package ships plain net10.0 and net11.0 builds,
which resolve from every MAUI platform target - Android, iOS, Mac Catalyst and Windows - with no workload on
the library side. Which registrations an app needs depends on how it draws its UI:
| Blazor Hybrid | Native (XAML) | |
|---|---|---|
| UI | Razor components in a BlazorWebView | XAML pages bound to the stores |
| Packages | Bit.Blex (+ Bit.Blex.Maui for Preferences) | Bit.Blex + Bit.Blex.Maui |
| Registration | builder.Services.AddBitBlexServices() - scoped, the WebView creates the scope | builder.UseBitBlex() - singletons, there are no scopes |
| Startup | <BlexProvider> around the router | The initializer UseBitBlex() registers, run by MauiApp.Build() |
| Re-rendering | BlexComponentBase, <BlexSelect>, <BlexView> | INotifyPropertyChanged bindings |
| Persistence | The WebView's localStorage, or Preferences | Preferences, or your own IBlexStorage |
| Redux DevTools | No extension in a WebView: EnableDevTools="false" | No browser at all |
Blazor Hybrid
A Blazor Hybrid app is a Blazor app inside a BlazorWebView: register Blex in
MauiProgram.cs exactly as a Blazor app does - the default scoped lifetimes are right, because
the WebView creates the scope - and wrap the root component's router in <BlexProvider>.
Everything else on this site applies unchanged: components, selectors, effects, queries, persistence,
undo and redo.
using Bit.Blex;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>();
builder.Services.AddMauiBlazorWebView();
// Scoped, exactly as in a Blazor app: the BlazorWebView creates the scope.
builder.Services.AddBitBlexServices(options => options.DevToolsName = "My App");
builder.Services.AddBitBlexStore<CounterStore>();
// Either the WebView's localStorage...
builder.Services.AddBitBlexLocalStoragePersistence();
// ...or, with Bit.Blex.Maui, OS-native Preferences:
// builder.Services.AddBitBlexPreferencesPersistence();
return builder.Build();
}
}
@* No browser extension exists inside a WebView, so the DevTools bridge is skipped outright. *@
<BlexProvider EnableDevTools="false">
<Router AppAssembly="typeof(MauiProgram).Assembly">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
</Found>
</Router>
</BlexProvider>
- DevTools. There is no browser extension inside a WebView; with
EnableDevToolsat its default (false) the bridge is never loaded, and turned on it detects the missing extension and disables itself. - Storage.
AddBitBlexLocalStoragePersistence()works - the WebView has alocalStorage- but it lives in the WebView's profile.AddBitBlexPreferencesPersistence()fromBit.Blex.Mauiwrites to the OS-native app preferences instead; itsIServiceCollectionoverload stays scoped, to match the rest. - The network. Requests leave from the device, so
<BlexProvider>follows the WebView'soffline/onlineevents and queries pause while offline, as in the browser.
Native (XAML)
A native MAUI app has no DI scopes: everything is resolved from the root provider for the life of the
process. Register Blex through the MauiAppBuilder extensions of Bit.Blex.Maui,
which register everything as singletons - the honest lifetime, and the one that keeps the
wiring legal when the container is built with ValidateScopes, which refuses to resolve a
scoped service from the root provider (exactly what the startup initializer has to do).
using Bit.Blex;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>();
builder.UseBitBlex(options => // manager + startup initializer
{
options.OnError = error => Debug.WriteLine($"[blex:{error.Source}] {error.Detail}: {error.Exception.Message}");
});
builder.AddBitBlexStore<CounterStore>();
builder.AddBitBlexPreferencesPersistence(); // OS-native Preferences storage
builder.AddBitBlexQueries(); // optional: the server-state cache
builder.AddBitBlexHistory(); // optional: undo and redo
builder.Services.AddTransient<MainPage>();
return builder.Build(); // stores registered, hydrated, history started
}
}
The core builder.Services.AddBitBlexStore<T>() still works and still defaults to scoped,
for Blazor; pass ServiceLifetime.Singleton if you call it directly - and give every Blex
registration the same lifetime.
Binding XAML to a store
Every store implements INotifyPropertyChanged, raised after each change with an
empty property name - "every property may have changed". A binding to a
[BlexComputed] property, or to an effect's XxxIsLoading, therefore stays fresh
too, though nothing assigns it. Bind to generated state, computed and effect-lifecycle properties alike:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:stores="clr-namespace:MyApp.Stores"
x:Class="MyApp.MainPage"
x:DataType="stores:CounterStore">
<VerticalStackLayout Spacing="12" Padding="24">
<Label Text="{Binding Count}" FontSize="32" />
<Label Text="{Binding DoubleCount}" /> <!-- [BlexComputed] -->
<Label Text="{Binding IsEven}" />
<Button Text="Increment" Clicked="OnIncrementClicked" />
<!-- An effect's lifecycle binds the same way, on a store with [BlexEffect] OnLoad:
<ActivityIndicator IsRunning="{Binding LoadIsLoading}" /> -->
</VerticalStackLayout>
</ContentPage>
public partial class MainPage : ContentPage
{
private readonly CounterStore _store;
// Resolved from the container: the very instance the startup initializer registered and hydrated.
public MainPage(CounterStore store)
{
InitializeComponent();
BindingContext = _store = store;
}
private void OnIncrementClicked(object? sender, EventArgs e) => _store.Increment();
}
This page listens to the counter's PropertyChanged, as a XAML binding does. Every action raises it once, with an empty name, and a binding re-reads whatever it shows - DoubleCount included, though no action assigns it.
What UseBitBlex does when the app is built
UseBitBlex() registers an IMauiInitializeService that mirrors what
<BlexProvider> does in Blazor. When MauiApp.Build() runs - before the first
page appears - it:
- resolves every store registered with
AddBitBlexStore, which attaches it to the manager; - rehydrates the persisted stores from
Preferences; - starts
BlexHistoryrecording, when one is registered. Unlike<BlexProvider>it does so after hydration, which completes before the first page can take a tap; either way undo's baseline is the state the user loaded.
None of it can stop the app from starting. A service it cannot resolve - typically a lifetime mismatch under
ValidateScopes - is reported through options.OnError with source
"startup" and a detail saying which registration to change; an unreadable payload is reported as
"persistence" and discarded; and the app runs on with lazily registered stores and declared
defaults. When Blex is registered with the core AddBitBlexServices instead,
services.AddBitBlexMauiInitializer() adds the initializer on its own.
Persisting to Preferences
AddBitBlexPreferencesPersistence() persists every Persist = true store to MAUI
Preferences through BlexPreferencesStorage - SharedPreferences on Android,
NSUserDefaults on iOS and Mac Catalyst, the local settings store on Windows. It takes the same
options as the browser providers: debounce, versioning and migrations,
Partialize, Merge, OnRehydrated, protection.
public sealed class FileStorage(string directory) : IBlexStorage
{
private string PathOf(string key) => Path.Combine(directory, key + ".json");
public async ValueTask<string?> GetAsync(string key, CancellationToken ct = default)
=> File.Exists(PathOf(key)) ? await File.ReadAllTextAsync(PathOf(key), ct) : null;
public async ValueTask SetAsync(string key, string value, CancellationToken ct = default)
=> await File.WriteAllTextAsync(PathOf(key), value, ct);
public ValueTask RemoveAsync(string key, CancellationToken ct = default)
{
File.Delete(PathOf(key));
return ValueTask.CompletedTask;
}
}
// MauiProgram.cs - registered first, so AddBitBlexPreferencesPersistence keeps it.
builder.Services.AddSingleton<IBlexStorage>(new FileStorage(FileSystem.AppDataDirectory));
builder.AddBitBlexPreferencesPersistence();
// ...and hydrated from app code, since it really awaits I/O:
await app.Services.GetRequiredService<BlexStatePersistor>().StartAsync();
- The first
IBlexStorageregistration wins, so register your own before callingAddBitBlexPreferencesPersistence(), with the same lifetime as the rest. - Hydrate an asynchronous storage yourself.
Preferencescompletes synchronously, so the startup initializer can wait on it. A storage that really awaits I/O should be hydrated from app code -await persistor.StartAsync()- rather than relying on that synchronous wait.
Queries in a native app
builder.AddBitBlexQueries() registers the server-state cache as a
singleton. There is no browser to report focus or the network, so tell the cache yourself: call
NotifyFocused() when a window activates, and NotifyOffline() /
NotifyReconnected() when Connectivity.ConnectivityChanged says the network went
or came back - fetches and mutations then wait for it instead of failing. A query observer and a
mutation implement INotifyPropertyChanged too, so XAML binds to them directly.
public partial class App : Application
{
private readonly BlexQueryClient _queries;
public App(BlexQueryClient queries)
{
InitializeComponent();
_queries = queries;
// The browser's offline/online events, by hand.
Connectivity.ConnectivityChanged += (_, e) =>
{
if (e.NetworkAccess == NetworkAccess.Internet) _queries.NotifyReconnected();
else _queries.NotifyOffline();
};
}
protected override Window CreateWindow(IActivationState? state)
{
var window = new Window(new AppShell());
// The tab becoming visible again: refetch the stale queries being watched.
window.Activated += (_, _) => _queries.NotifyFocused();
return window;
}
}
// A page binds to a query observer like to a store - BlexQuery<T> is INotifyPropertyChanged:
BindingContext = queries.Query(["products"], ct => api.GetProductsAsync(ct)); // {Binding Data}, {Binding IsLoading}The UI thread
Stores are not synchronized. In Blazor, <BlexProvider> binds the renderer's dispatcher to
the manager; a native app has no provider, so nothing is checked unless you assign an
IBlexDispatcher yourself. Over MAUI's own dispatcher it is two lines - and then
manager.InvokeAsync(...) moves a change from a timer or a background task onto the UI thread,
and a change made off it anyway is reported instead of racing the bindings.
/// <summary>MAUI's UI-thread dispatcher, as the IBlexDispatcher the manager checks changes against.</summary>
public sealed class MauiBlexDispatcher(IDispatcher dispatcher) : IBlexDispatcher
{
public bool CheckAccess() => !dispatcher.IsDispatchRequired;
public Task InvokeAsync(Func<Task> workItem) => dispatcher.DispatchAsync(workItem);
}
public App(BlexManager manager)
{
InitializeComponent();
manager.Dispatcher = new MauiBlexDispatcher(Dispatcher);
}
// From a timer or a background service:
await manager.InvokeAsync(() => orders.Add(order));API
BitBlexMaui (namespace Bit.Blex)
| Extension | Description |
|---|---|
builder.UseBitBlex(Action<BlexOptions>?) |
The manager and middleware as singletons (AddBitBlexServices with ServiceLifetime.Singleton), plus the startup initializer. |
builder.AddBitBlexStore<TStore>() |
A store as a singleton, resolvable as itself and as IBlexStore. |
builder.AddBitBlexPreferencesPersistence(Action<BlexPersistenceOptions>?) |
Persistence to Preferences, as a singleton; adds the initializer if it is not there yet. |
builder.AddBitBlexQueries(Action<BlexQueryClientOptions>?) |
The server-state cache, as a singleton. |
builder.AddBitBlexHistory(maxEntries, filter?, groupBy?) / (scope, ...) / AddBitBlexHistory<TStore>(...) |
Undo and redo, app-wide, scoped to some stores, or per store type - as singletons. See Undo & redo. |
services.AddBitBlexPreferencesPersistence(configure?, lifetime = Scoped) |
The IServiceCollection form, scoped by default - for Blazor Hybrid. |
services.AddBitBlexMauiInitializer() |
The startup initializer alone, for an app that registers Blex with the core calls. Idempotent. |
BlexPreferencesStorage
| Member | Description |
|---|---|
BlexPreferencesStorage() |
Over Preferences.Default. |
BlexPreferencesStorage(IPreferences) |
Over the preferences you hand it - a fake one in a test, or a shared container. |
GetAsync / SetAsync / RemoveAsync |
IBlexStorage, completing synchronously. |