Skip to content

Reference

API reference

Every public type Blex ships, grouped by assembly and namespace, with a pointer to the page that explains it.

Members are documented in depth on the topic pages - this page is the index. Everything here is also XML-documented, so IntelliSense carries the same text.

Blex - attributes

Namespace Bit.Blex. These are the entire authoring surface of a store.

Type Description
BlexStoreAttribute Marks a partial class as a store. Properties: Name, Persist, Version, EnforceActions, RollbackOnError. See Stores & state.
BlexStateAttribute Marks a field as reactive state. Property: Persist (set false to keep the field out of storage). See Stores & state and Persisting only part of a store.
BlexComputedAttribute Marks a parameterless ComputeXxx()/GetXxx() method as memoized derived state. See Computed state.
BlexActionAttribute Marks an OnXxx method as an action. Property: Name. See Actions.
BlexEffectAttribute Marks an async OnXxx method as an effect. Properties: Name, Concurrency, DebounceMilliseconds, RetryCount, RetryDelayMilliseconds, TimeoutMilliseconds. See Effects.
BlexEffectConcurrency Enum: Parallel, Latest, Drop, Queue. See Effects.
At a glance
[BlexStore(Name = "cart", Persist = true)]
public partial class CartStore
{
    [BlexState]    private IReadOnlyList<CartLine> _lines = [];

    [BlexComputed] private decimal ComputeTotal() => Lines.Sum(l => l.Total);

    [BlexAction]   private void OnAdd(CartLine line) => Lines = [.. Lines, line];

    [BlexEffect(Concurrency = BlexEffectConcurrency.Drop)]
    private async Task OnCheckout(CancellationToken ct) => await _api.CheckoutAsync(Lines, ct);
}

Blex - core

Type Description
IBlexStore The store contract: Name, Persist, StateChanged, SerializeState(), DeserializeState().
BlexStoreBase Base class for every store. Change notification, batched dispatch, Batch, ResetState, RestoreState, InstanceKey, ActionDescriptors / FindAction, Dispose() (cancels in-flight effects), INotifyPropertyChanged (raised with an empty name after every change, for XAML) and the protected hooks the generator uses. See Stores & state.
BlexManager The central manager: store registry, CreateScope, middleware pipeline, action subscriptions (typed ones included), DispatchAsync by name, global state capture and restore, ResetAll, TimeProvider, Dispatcher / InvokeAsync, WhenAsync, Transaction, CreateSelectorFamily, DetectInPlaceMutations, DevTools connection, error sink. See Cross-store coordination.
BlexActionDescriptor One action described as data: Name, StoreType, ParameterNames, Matches(...), an untyped InvokeAsync(store, args), and the static GetArg<T> / GetArgOrDefault<T> generated descriptors read a payload with. See Typed actions.
BlexAction<TStore> The generated descriptor of a parameterless action (CounterStore.Actions.Increment): InvokeAsync(store).
BlexAction<TStore, TPayload> The generated descriptor of an action with arguments: TryGetPayload, GetPayload, ReadPayload, InvokeAsync(store, payload). The payload is the single argument, or a tuple named after the parameters.
BlexStoreScope<TStore> One instance of a store registered under "{name}:{key}" by manager.CreateScope: Store, Key, Dispose(). See Scoped stores.
BlexActionContext What observers receive after an action: Store, ActionName, QualifiedName, Args, Sequence, Timestamp, GlobalState.
BlexPreActionContext What middleware receives before an action, plus IsCancelled and Cancel().
BlexActionErrorContext What the error hooks receive when an action body throws: Store, ActionName, QualifiedName, Args, Exception, Timestamp. See Middleware.
BlexActionArg readonly record struct (string Name, object? Value) - one captured action argument.
BlexOptions Configuration passed to AddBitBlexServices: DevToolsName, sanitizers, RedactDevToolsKeys, UseMiddleware, UseFilter (typed overloads included), OnError, OnActionError, TimeProvider, ReportOffDispatcherChanges, DetectInPlaceMutations, UseLogging.
BlexComparers Collection equality for selector subscriptions: Sequence<T>() and Set<T>(). See Components & selectors.
BlexSelector<T> A lazy, memoized derived value over the whole state tree, created with manager.CreateSelector(...): Value, IsValid, Invalidate(), Dispose(). See Cross-store coordination.
BlexSelectorFamily<TArg, T> One memoized selector per argument, created with manager.CreateSelectorFamily(...) and read with family[arg]; bounded by MaxSize (least recently read evicted first). Remove, Invalidate, Clear, IsValid(arg), Count. See Cross-store coordination.
BlexError readonly record struct (string Source, Exception Exception, string? Detail) - an isolated pipeline failure. See Error isolation.
BlexJson The shared JsonSerializerOptions used by generated serialization: Options, Configure(...) (a source-generated context for trimming and AOT, custom converters) and Reset(). See Installation.
IBlexDevTools The DevTools sink abstraction: Init, Send and the defaulted SendLiftedState (an imported session, handed back). See DevTools.
BlexDiagnostics SourceName ("Bit.Blex"): the ActivitySource and Meter every action, effect and query fetch is traced and measured on. See Logging and tracing.
IBlexDispatcher The execution context the state belongs to: CheckAccess(), InvokeAsync(...). <BlexProvider> binds the renderer's. See Threads and the dispatcher.

Blex - middleware

Type Description
IBlexMiddleware OnAction(BlexActionContext) plus the defaulted BeforeAction(BlexPreActionContext) and OnActionError(BlexActionErrorContext). See Middleware.
BlexDelegateMiddleware Forwards each applied action to an Action<BlexActionContext>.
BlexFilterMiddleware Vetoes an action when the supplied predicate returns false.
BlexLoggingMiddleware Writes actions, action failures and isolated failures to an ILogger; registered by options.UseLogging().

Blex - collections

Type Description
BlexEntityState<TEntity, TKey> Immutable normalized state: Ids, Entities, All, Count, Contains, Find, TryGet, this[id], Empty.
BlexEntityAdapter<TEntity, TKey> CRUD over that state, plus SelectId and SortComparer. See Entity adapter.

Blex - persistence

Type Description
IBlexStorage Async key/value sink: GetAsync, SetAsync, RemoveAsync.
IBlexExternalStorageChange Optional companion to IBlexStorage: reports keys written by another instance (another tab), enabling SyncAcrossTabs.
IBlexStorageSuspension Optional companion to IBlexStorage: reports the page it lives on being hidden or unloaded, so a debounced save is written before the page is gone.
IBlexStateProtector Encrypts and tamper-proofs persisted payloads (ProtectAsync/UnprotectAsync, which returns null for a value it cannot vouch for). Set BlexPersistenceOptions.Protector or register one in DI. See Persistence.
BlexPersistenceOptions KeyPrefix, DebounceInterval, DebounceMaxDelay, Version, Migrate, Merge, Partialize, OnRehydrated, SkipHydration, SyncAcrossTabs, OnExternalChange, Protector.
BlexStatePersistor The coordinator: StartAsync, RehydrateAsync, FlushAsync, ClearAsync, DisposeAsync, plus HasHydrated / Hydrated / WhenHydratedAsync(). See Persistence.

Blex - history

Type Description
BlexHistory In-app undo/redo over the state tree, or over the stores a scope admits: Undo/Redo, Jump/JumpToPast/JumpToFuture, UndoLabels/RedoLabels, Checkpoint, IsScoped/Covers, plus an optional filter and groupBy. See Undo & redo.
BlexHistory<TStore> Undo/redo for one store type only, every instance of it included. Registered with AddBitBlexHistory<TStore>(). See Scoping history.

Blex - queries

Namespace Bit.Blex.Query: the server-state cache, kept apart from stores on purpose.

Type Description
BlexQueryClient The server-state cache: Query, InfiniteQuery, FetchAsync, PrefetchAsync, GetQueryData / SetQueryData, TryGetQueryData, Optimistic, Mutation, InvalidateAsync, RefetchAsync, Cancel, Remove / Clear, NotifyFocused, NotifyOffline / NotifyReconnected / IsOnline, GetQueries / FetchingCount / CacheChanged, Dehydrate / Hydrate, Options. See Server state & queries.
BlexQueryKey An ordered list of parts identifying a query (["todos", 42]): value equality, StartsWith for prefix invalidation.
BlexQuery / BlexQuery<T> An observer of one cached query: Data, Status, FetchStatus, Error, IsLoading, IsRefetching, IsStale, IsPlaceholderData, RefetchAsync, WhenSettledAsync, Update, Changed.
BlexInfiniteQuery<TPage, TParam> An observer of a paged query (InfiniteQuery / UseInfiniteQuery): Pages, PageParams, HasNextPage, IsFetchingNextPage, FetchNextPageAsync, plus everything a BlexQuery reports. See Server state & queries.
BlexInfiniteData<TPage, TParam> The data of a paged query - its Data, and what GetQueryData and SetQueryData see under its key: Pages, the PageParams each was fetched with, and Empty.
BlexQueryOptions Per-observer: StaleTime, GcTime, RetryCount, RetryDelay, Enabled, RefetchInterval, RefetchOnMount, RefetchOnFocus, KeepPreviousData, NetworkMode.
BlexQueryClientOptions The defaults: StaleTime (0), GcTime (5 min), RetryCount (3), RetryDelay (1 s), NetworkMode (Online: requests wait while offline), SyncAcrossTabs (off: invalidations stay in their tab).
BlexNetworkMode Enum: Online (the default: requests wait while the app is offline - paused, not failed) and Always (requests run whatever the network, for data that does not come from it).
BlexQueryStatus / BlexFetchStatus Pending/Error/Success, and independently Idle/Fetching.
BlexQueryInfo A cached query as GetQueries() reports it, for inspection.
BlexMutation<TArg, TResult> A change sent to the server: MutateAsync (never throws), Status and IsIdle / IsPending / IsSuccess / IsError, IsPaused, Data, Error, Arg, Reset, Changed / PropertyChanged.
BlexMutationOptions<TArg, TResult> OnMutate (returns the rollback), OnSuccess, OnError, OnSettled, Invalidates, RetryCount, RetryDelay, NetworkMode.
BlexMutationStatus Idle, Pending, Error, Success.
IBlexRollback / BlexRollback What a failed mutation undoes; BlexRollback.From(action) and Combine(...).
BlexOptimisticUpdate<T> Returned by Optimistic: Key, Value, Rollback() - which restores only while the cache still holds this update's value, and refetches otherwise.

Blex - extension methods

Type Description
BitBlex AddBitBlexServices, AddBitBlexStore<T>, AddBitBlexPersistence, AddBitBlexHistory (with an optional scope), AddBitBlexHistory<TStore>, AddBitBlexQueries.
BlexStoreSubscriptionExtensions store.Subscribe(selector, onChanged, comparer, fireImmediately) in both single-value and previous/current forms. See Components & selectors.
BlexObservableExtensions store.Observe(selector, comparer) and manager.ObserveActions() as IObservable<T>, for Rx. See Components & selectors.

Blex - Blazor

Namespace Bit.Blex.Blazor, in the same Bit.Blex package. Everything that touches JavaScript or the Blazor render tree lives here; the rest of Blex never does.

Type Description
BlexProvider Root component: registers stores, restores prerendered and persisted state, starts history, connects DevTools. Parameters: EnableDevTools, PersistComponentState, ChildContent.
BlexComponentBase Optional component base with Subscribe, selector Subscribe, UseQuery, UseInfiniteQuery, Watch, OwnsSubscription, RenderInterval (render throttling) and a Dispose(bool) hook.
BlexSelect<TValue> Renders its content from a projection of a store and re-renders only that content, only when the projection changes. Parameters: Store, Selector, Comparer, RenderInterval, ChildContent. See Components & selectors.
BlexView Re-renders its content on any change to Store / Stores - no base class required. Parameters: Store, Stores, RenderInterval, ChildContent. See Throttling renders.
BlexScope<TStore> Gives its content its own instance of a store - created from DI, registered as "{name}:{key}", cascaded, and disposed with the scope. Parameters: Key, Factory, ChildContent. See Scoped stores.
BlexBrowserStorage IBlexStorage over localStorage/sessionStorage through a small JS module. Also implements IBlexExternalStorageChange via the browser's storage event, which powers SyncAcrossTabs, and IBlexStorageSuspension via pagehide and visibilitychange.
BlexBrowserStorageKind Enum: Local, Session.
BitBlexBlazor AddBitBlexLocalStoragePersistence, AddBitBlexSessionStoragePersistence.
BlexComponentStatePersistence Bridges stores to Blazor's PersistentComponentState for the prerender-to-interactive handoff.
BlexReduxDevToolsConnector The IBlexDevTools implementation that talks to the browser extension.
BlexRendererDispatcher A renderer's Dispatcher as an IBlexDispatcher; what <BlexProvider> binds to the manager.
BlexQueryView<TData> Renders a cached query from markup. Parameters: Key, Fetch, Options, ChildContent (with the data), LoadingContent, ErrorContent. See Server state & queries.

Bit.Blex.Maui

Namespace Bit.Blex.Maui. A native .NET MAUI app has no <BlexProvider> and no DI scopes, so these register Blex as singletons; a Blazor Hybrid app keeps the scoped core registrations and only takes the preferences storage from here.

Type Description
BitBlexMaui UseBitBlex (the manager, plus the startup initializer that registers the stores, rehydrates them and starts history when the app is built), AddBitBlexStore<TStore>, AddBitBlexPreferencesPersistence, AddBitBlexHistory (with an optional scope), AddBitBlexHistory<TStore>, AddBitBlexQueries, AddBitBlexMauiInitializer. See .NET MAUI.
BlexPreferencesStorage IBlexStorage over MAUI Preferences: SharedPreferences on Android, NSUserDefaults on iOS and Mac Catalyst, the local settings store on Windows.

Bit.Blex.Testing

Namespace Bit.Blex.Testing.

Type Description
BlexTestHarness<TStore> Store + manager + action log in one object, plus Failures, Register and a settable TimeProvider.
BlexTestHarness Static factory: For<TStore>(), For(store), WithMiddleware, WithFilter.
BlexActionLog Records dispatches: Actions, Last, Count, Names, QualifiedNames, Contains, CountOf (by name or descriptor), PayloadsOf, Clear.
BlexRecordedAction One recorded dispatch with its store, names, sequence, state snapshot and args, and IsNested for one that ran inside another action's body. See Replaying actions.
BlexTestExtensions RecordActions, Snapshot, store.WaitForAsync, manager.WaitForAsync, CountNotifications, manager.ReplayAsync. See Testing.

Generated members, by declaration

What the generator adds to your partial class, for each thing you declare.

You declareGenerated
[BlexStore] on partial class Foo partial class Foo : BlexStoreBase, override string Name => base.WithInstanceKey("Foo") (the declared Name, else the class name as written, plus :{key} for a scoped instance), override JsonObject SerializeState(), override void DeserializeState(JsonObject), and override DescribeActions() listing the store's action descriptors - its actions and effects, plus a "Set Foo" per state property
[BlexStore(Persist = true)] override bool Persist => true
[BlexStore(Persist = true, Version = 2)] override int PersistVersion => 2 - the store's saved state is versioned on its own, not by options.Version
[BlexStore(EnforceActions = true)] every state setter is private set, override bool EnforcesActions => true, and no "Set Foo" descriptors
[BlexStore(RollbackOnError = true)] override object?[]? CaptureRollbackState() and override void ApplyRollbackState(object?[]) - the shallow copy of the state fields a synchronous action starts from, put back when it throws
[BlexState] private T _foo; public T Foo { get; set; } - the setter routes through SetState; the field is included in both snapshot methods
[BlexState(Persist = false)] private T _foo; the same property, and "Foo" in an override TransientStateKeys - kept out of durable persistence
[BlexState(Comparer = nameof(C))] private T _foo; the same property, whose setter passes C to SetState to decide whether an assignment changes anything
[BlexComputed] T ComputeFoo() public T Foo { get; } plus __FooValid / __FooValue, an entry in InvalidateComputed(), and one in InvalidateComputed(string?) under every state property its body reads
[BlexAction] void OnFoo(A a) public void Foo(A a)
[BlexAction] Task OnFoo(A a) public Task Foo(A a)
[BlexEffect] Task OnFoo(A a) public Task Foo(A a), public bool FooIsLoading, public Exception? FooError
[BlexEffect] Task OnFoo(A a, CancellationToken ct) the above, plus public void CancelFoo() - and note the token is not on the public signature - and an entry in the override CancelEffects() that disposing the store calls
[BlexEffect(DebounceMilliseconds = 300)] Task OnFoo(A a) the effect members, plus public void CancelFoo() even without a token - it cancels the invocation still waiting out its quiet period
any [BlexAction] or [BlexEffect] a field in the nested public static class Actions: BlexAction<Foo> Bar for OnBar(), BlexAction<Foo, A> Bar for OnBar(A a), BlexAction<Foo, (A A, B B)> Bar for OnBar(A a, B b). Not generated - with warning BLEX020 - when the store already has a member named Actions.

Reserved names

A generated member may not take one of these - they are inherited from BlexStoreBase or emitted by the generator itself. Collisions are reported as BLEX005. The name Actions is different: taking it costs only the typed descriptors (BLEX020). A store may write its own override of one of them only where the generator writes none: its own PersistVersion next to [BlexStore(Version = n)], or its own SerializeState in any store, is BLEX026.

Reserved
Name                    Persist                 PersistVersion
StateChanged            PropertyChanged         SerializeState
DeserializeState        InvalidateComputed      NotifyRestored
SetState                SetEffectState          BeginEffect
EndEffect               DebounceEffectAsync     RunEffectAttemptsAsync
Dispatch                DispatchAsync           BeginAction
DispatchApprovedAsync   Batch                   ResetState
RestoreState            IsRestoring             IsObserved
Dispose                 IsDisposed              CancelEffects
InstanceKey             WithInstanceKey         TimeProvider
ActionDescriptors       FindAction              DescribeActions
EnforcesActions         TransientStateKeys      CaptureRollbackState
ApplyRollbackState

JSON conventions

Snapshots use BlexJson.Options: JsonSerializerDefaults.Web, case-insensitive property matching and enums written as strings. Slices are keyed by the generated property name (Count, not _count), and the global tree is keyed by store name.

// A single store's SerializeState()
{ "Count": 3, "Step": 1 }

// BlexManager.CaptureGlobalState()
{
  "counter":  { "Count": 3, "Step": 1 },
  "contacts": { "Contacts": { "ids": [1, 2], "entities": { "1": { }, "2": { } } } },
  "settings": { "Accent": "violet", "Density": "Comfortable" }
}

// A persisted slice with options.Version > 0
{ "__blexVersion": 1, "state": { "Accent": "violet" } }

// A persisted slice of a store with a version of its own ([BlexStore(Version = n)])
{ "__blexStoreVersion": 2, "state": { "View": "grid" } }
An unhandled error has occurred. Reload 🗙