Core concepts
Scoped stores
Most state belongs to the app. Some belongs to one part of the page - and needs its own instance for every part that shows it.
One instance is not always enough
AddBitBlexStore<T> gives each DI scope one instance of a store, keyed in the
state tree, in DevTools and in storage by its name. That is right for a cart or a profile. It is
wrong for the form inside each of two open dialogs, one editor per tab, or a wizard that must
start fresh every time it opens: a second instance under the same name would share the first
one's slice, its DevTools entry and its storage key - and creating it by hand means remembering
to register it, unregister it and dispose it.
A scoped store is one instance among several, registered under its own name -
"{name}:{key}" - for as long as the part of the page that owns it is alive.
<BlexScope>
Wrap the part of the page that owns the state. The scope creates an instance from DI when it appears (constructor dependencies are resolved as usual), registers it with the manager, cascades it to every descendant, and unregisters and disposes it when it goes away - cancelling any effect still in flight.
<BlexScope TStore="CheckoutStore" Key="@OrderId">
<CheckoutSteps />
</BlexScope>
@* Or use the instance inline, through the content's context: *@
<BlexScope TStore="DraftStore" Key="notes" Context="draft">
<p>@draft.Words words</p>
</BlexScope>
@* A store that needs an argument from the page: *@
<BlexScope TStore="DocumentStore" Key="@DocumentId"
Factory="sp => new DocumentStore(sp.GetRequiredService<DocumentsApi>(), DocumentId)">
<Editor />
</BlexScope>
@inherits BlexComponentBase
<input value="@Checkout.Email" @oninput="e => Checkout.SetEmail(e.Value?.ToString() ?? string.Empty)" />
@code {
// Whichever instance the enclosing scope created.
[CascadingParameter] public CheckoutStore Checkout { get; set; } = default!;
protected override void OnInitialized() => Subscribe(Checkout);
}
The same store, the same editor component, two scopes. Each keeps its own state; the Inspector's feed shows draft:left/Write and draft:right/Write as separate slices of the tree.
draft:left
draft:right
A scoped store type is created by its scopes, not resolved from the container, so it has no
AddBitBlexStore registration. Its constructor dependencies still come from DI;
for one that needs an argument from the page, pass a Factory.
Keys
The key is an id of whatever the store is about - an order id, a document id, a tab index.
Changing Key replaces the instance: the outgoing one is unregistered (writing any
debounced save it still owes first) and a new one is created for the new key. The descendants
are keyed to the instance too, so per-instance state of their own does not leak from one
document to the next. Without a Key, a key unique within the manager is assigned
and kept for the scope's lifetime - and the instance is not persisted, since no later scope
could find its state.
Switch documents and type: each document has its own draft. The store persists and the keys are stable, so reload the page and every draft comes back - hydrated the moment its scope registers it.
draft:doc-1
A wizard, a dialog that must start empty: no Key at all. Open the scratchpad and write something; close it and the instance is unregistered and disposed; open it again and it is a new one, under a newly assigned key, with nothing in it - an instance whose key was assigned for it is never persisted.
Closed - no draft:… instance exists for it now. Check the Inspector's state tree.
Without Blazor: CreateScope
<BlexScope> is a thin layer over BlexManager.CreateScope, which
works anywhere - a MAUI page, a worker, a test.
using var editor = manager.CreateScope(new DocumentStore(api), key: documentId);
editor.Store.Rename("Draft"); // recorded as "document:42/Rename"
manager.GetStore("document:42"); // the same instance
// Dispose (or leave the using block): unregistered, pending save written, effects cancelled.
BlexManager
| Member | Description |
|---|---|
BlexStoreScope<TStore> CreateScope<TStore>(TStore store, string? key = null) |
Registers a not-yet-registered store as "{name}:{key}". Without a key, one unique within the manager is assigned, and the instance is not persisted. Throws for an empty key, a store that is already registered, and a hand-written store whose name ignores the key. |
IBlexStore? GetStore(string name) |
The store registered under that name - "draft:left". |
event Action<IBlexStore>? StoreRegistered / StoreUnregistered |
Raised as stores join and leave the manager. Persistence uses them. |
BlexStoreScope<TStore>
| Member | Description |
|---|---|
TStore Store |
The scoped instance. |
string Key |
Its instance key; the store's name is "{name}:{Key}". |
bool IsDisposed |
Whether the scope has been disposed. |
void Dispose() |
Unregisters the store - persistence writes its pending save - and then disposes it, cancelling its effects. Idempotent. |
<BlexScope TStore>
| Parameter | Description |
|---|---|
string? Key |
The instance key. Changing it replaces the instance and its subtree. Omitted: a unique key, kept for the scope's lifetime, and no persistence. |
Func<IServiceProvider, TStore>? Factory |
Creates the store when DI alone cannot. Defaults to constructing TStore with its dependencies from DI. |
RenderFragment<TStore>? ChildContent |
The content, with the instance as its context. Descendants receive it as a [CascadingParameter] too. |
TStore Store |
Not a parameter: the instance, for code holding a @ref to the scope. |
Persistence
A scoped store marked Persist = true is saved under its keyed name and hydrated as
soon as it registers - not only at startup, which is when every other store is hydrated. The
storage key is that name after the KeyPrefix (blex: by default); this
site sets blex-docs:, so the second document above is saved as
blex-docs:draft:doc-2.
- Give it a stable key. The next scope for the same entity finds the state the last one left. An assigned key (
#1,#2, ...) counts from 1 again in every session and every tab, so an instance keyed that way is not persisted at all - its state could only ever be found by an unrelated instance that drew the same number. - Its saves wait for hydration. Until its stored state has been read, nothing it does is written - writing its declared defaults first would overwrite the user's data. This mirrors startup, where the stored state wins over anything dispatched before it landed. If the read finds nothing stored, what was changed meanwhile is written then; if it fails, the saves keep waiting until
RehydrateAsyncreads it. - Leaving writes what it owes. With a debounce interval, a scope disposed before the interval elapses still has its last changes written as it unregisters.
OnRehydratedfires for a late store too, with its keyed name. WithSkipHydration, a late store waits forRehydrateAsynclike every other.
A full citizen
Scoping changes the name and the lifetime, nothing else. A scoped instance's actions pass the
filters, reach middleware and subscribers, stream to DevTools as draft:left/Write
and become undo steps.
- A generated descriptor matches every instance:
DraftStore.Actions.Write.Matches(ctx)is true for the left draft and the right one, andctx.Storesays which. BlexHistory<DraftStore>covers all instances. An undo cannot revert an instance to a state from before it registered - a snapshot taken then has no slice for it, so it is left alone.- Dispatch by name uses the keyed name:
manager.DispatchAsync("draft:left/Write", ...). manager.GetStore<DraftStore>()returns one of the instances; look a specific one up by name instead -manager.GetStore("draft:left").
The handoff from a prerendered page to the interactive one covers the stores
<BlexProvider> knows about at startup. A scoped instance is created again by
the interactive render, so it starts from its declared state - or, when it persists, from
storage.
A generated store's Name includes the instance key. A hand-written
BlexStoreBase subclass must return WithInstanceKey("its-name") from
Name to be scopable; CreateScope throws
NotSupportedException otherwise, rather than letting every instance share one slice.