Migrating from Ducky 1.x
This guide takes an app from Ducky 1.0.292, the last published 1.x (Ducky, Ducky.Blazor and Ducky.Generator on nuget.org), to Ducky 2.0. Ducky 2.0 is a rewrite: the concepts carry over (slices, actions, effects, selectors, DuckyComponent<TState>), most type names do not.
Every snippet on this page comes from the compiled sample in docs/migration/samples/ducky-1x: Before builds against the 1.0.292 packages, After is the same app on Ducky 2.0, and After.Tests holds its tests and one test per behaviour change below.
Checklist
Target
net11.0: Ducky 2.x does not run on .NET 10 or earlier, so upgrade the app's SDK andTargetFrameworkfirst. Then update the packages:DuckyandDucky.Blazorto 2.0, addDucky.Testingto test projects, and removeDucky.Generator. Its generators now ship insideDucky; its final 2.0.0 package only raises DUCKY900 to say so.Fix each DUCKYM error (see Tombstones). Each one names the 2.0 replacement and links its page.
Add a
JsonSerializerContextand pass it withUseJson(AppJson.Default). It may start empty: DUCKY006 then lists every[DuckyAction]and slice state type missing from it, and DUCKY306 at startup names any persisted or prerendered state type still missing.AppJson.csfrom a tested file // Checklist step 3: a JsonSerializerContext passed with UseJson(AppJson.Default). It may start empty: DUCKY006 then lists // each [DuckyAction] and slice state type it lacks. [JsonSerializable(typeof(CounterState))] [JsonSerializable(typeof(Increment))] [JsonSerializable(typeof(Reset))] public sealed partial class AppJson : JsonSerializerContext;Replace the registration chain (see Registration).
Run the app's tests, then read Behaviour changes: they compile unchanged and behave differently.
Before and after
State, actions and reducers
// Ducky 1.x: every state implements the IState marker; a record deriving from SliceReducers<TState> reduces it.
public sealed record CounterState(int Value) : IState;
[DuckyAction]
public sealed record Increment(int Amount = 1);
[DuckyAction]
public sealed record Reset;
public sealed record CounterReducers : SliceReducers<CounterState>
{
public CounterReducers()
{
On<Increment>((state, action) => new CounterState(state.Value + action.Amount));
On<Reset>(GetInitialState);
}
public override CounterState GetInitialState() => new(0);
}// Ducky 2.0: any record is a state (no IState); a sealed Slice<TState> declares the initial state and its reducers.
public sealed record CounterState(int Value);
[DuckyAction]
public sealed record Increment(int Amount = 1);
[DuckyAction]
public sealed record Reset;
public sealed class CounterSlice : Slice<CounterState>
{
public CounterSlice()
{
On<Increment>((state, action) => new CounterState(state.Value + action.Amount));
On<Reset>(_ => Initial);
}
protected override CounterState Initial => new(0);
}[DuckyAction] is now Ducky.DuckyActionAttribute (using Ducky; replaces global using Ducky.Generators;), and its dispatch helpers are {Record}DispatchExtensions in the record's namespace, on anything that dispatches: IStore, an effect's EffectContext, a TestStore.
Effects
// Ducky 1.x: an AsyncEffect<TAction> reads the root state and dispatches through its own Dispatch.
public sealed class ResetAboveTen : AsyncEffect<Increment>
{
public override Task HandleAsync(Increment action, IRootState rootState)
{
if (rootState.GetSliceState<CounterState>().Value > 10)
{
Dispatch(new Reset());
}
return Task.CompletedTask;
}
}// Ducky 2.0: Effect<TAction> reads the snapshot and dispatches through its context.
public sealed class ResetAboveTen : Effect<Increment>
{
public override Task Handle(Increment action, EffectContext context, CancellationToken cancellationToken)
{
if (context.State.Get<CounterState>().Value > 10)
{
context.Reset(); // generated from [DuckyAction]: context.Dispatch(new Reset())
}
return Task.CompletedTask;
}
}An effect takes its services through its constructor and gets a CancellationToken; ctx.Run covers the started/succeeded/failed triad, and Policy picks Merge, Switch, Exhaust or Queue (see Effects).
Selectors
// Ducky 1.x: a memoized selector over the slice state.
public static class CounterSelectors
{
public static readonly Func<CounterState, bool> IsPositive = MemoizedSelector.Create<CounterState, bool>(state => state.Value > 0);
}// Ducky 2.0: Selector.Define over the snapshot; Create() gives each consumer its own memoized function.
public static class CounterSelectors
{
public static readonly SelectorDef<bool> IsPositive = Selector.Define((StateSnapshot s) => s.Get<CounterState>().Value, value => value > 0);
}Components
// Ducky 1.x: the component subscribes to its slice and dispatches through the generated Dispatcher.X() helpers.
public sealed class CounterView : DuckyComponent<CounterState>
{
public int Value => State.Value;
public int Renders { get; private set; }
public void Increment() => Dispatcher.Increment(2);
protected override void OnAfterSubscribed() => Renders++;
}// Ducky 2.0: the component dispatches through Store.X() (no Dispatcher property); OnInitialized is no longer sealed.
public sealed class CounterView : DuckyComponent<CounterState>
{
private Selection<bool>? _isPositive;
public int Value => State.Value;
public bool IsPositive => _isPositive!.Value;
public int Initializations { get; private set; }
public void Increment() => Store.Increment(2);
protected override void OnInitialized()
{
_isPositive = Select(CounterSelectors.IsPositive.Create());
Initializations++; // what OnAfterSubscribed did, after the Select calls
}
protected override void BuildRenderTree(RenderTreeBuilder builder) => builder.AddContent(0, Value);
}Registration
// Ducky 1.x: options bound from the "Ducky" configuration section; slices and effects found by assembly scan.
services.AddDucky(configuration, options => options.AssemblyNames = ["Ducky1x.Before"]);// Ducky 2.0: one builder; the generated AddDuckyGenerated_{Assembly}() replaces the assembly scan.
services.AddDucky(ducky => ducky
.AddDuckyGenerated_Ducky1x_After()
.UseJson(AppJson.Default)
.AddBlazor());Reading state
// Ducky 1.x: the root state, read through the store's observable.
public static int ReadCount(DuckyStore store) =>
store.RootStateObservable.CurrentValue.GetSliceState<CounterState>().Value;// Ducky 2.0: the store's current snapshot.
public static int ReadCount(IStore store) => store.State.Get<CounterState>().Value;Tombstones (DUCKYM001 to DUCKYM008)
A 1.x type that user code derives from, implements or calls statically is kept as a member-less interface in its 1.x namespace, marked obsolete as an error. The compiler then reports its DUCKYM code on each use, with the replacement in the message. The tombstones are removed in 3.0.
| ID | 1.x type (namespace) | Ducky 2.0 |
|---|---|---|
| DUCKYM001 | IState, IKeyedAction (Ducky) |
delete the base: any object is an action or a state |
| DUCKYM002 | SliceReducers<TState>, ISlice<TState> (Ducky) |
sealed class X : Slice<TState> with protected override TState Initial => |
| DUCKYM003 | AsyncEffect<TAction>, IAsyncEffect (Ducky) |
Effect<TAction>: constructor injection, Handle(action, EffectContext, CancellationToken), ctx.Dispatch, ctx.State |
| DUCKYM004 | IReactiveEffect (Ducky) |
Ducky.Reactive's ReactiveEffect (R3 Observable<object>) |
| DUCKYM005 | MemoizedSelector (Ducky) |
Selector.Define(...) + def.Create() |
| DUCKYM006 | Fsa, Fsa<TPayload>, Fsa<TPayload, TMeta>, FsaError, FsaError<TMeta>, FsaMeta<TMeta> (Ducky) |
a plain record (no base type) |
| DUCKYM007 | NormalizedState<TKey, TEntity, TState> (Ducky) |
an EntityState<TKey, TEntity> member of the state record |
| DUCKYM008 | DuckyLayout<TState> (Ducky.Blazor) |
the non-generic DuckyLayout + Select in OnInitialized |
Mapping table
Every other public type of Ducky 1.0.292 and Ducky.Blazor 1.0.292 (docs/migration/ducky-1x-api.txt), then the APIs that changed shape. The Docs build fails when a listed type has neither a tombstone nor a row here. Rows and sections marked (dev) cover APIs of the unreleased 1.x dev branch, absent from 1.0.292.
| 1.x | Ducky 2.0 |
|---|---|
IDispatcher, Dispatcher (Ducky) |
inject IStore, which is an IDispatcher (Dispatch, DispatchAsync); the dispatcher itself is internal |
IDispatcher.ActionStream |
a Ducky.Reactive ReactiveEffect (its actions observable) |
IDispatcher.LastAction |
TestStore.Processed in tests, or a Middleware in the app |
DuckyStore, DuckyStoreFactory, ObservableSlices (Ducky) |
inject IStore; AddDucky builds it. RootStateObservable becomes Store.Select(selector, onChange) |
Store.StateChanged += (dev) |
Store.Select(s => s, onChange); dispose the Selection to unsubscribe |
IRootState, RootState (Ducky) |
StateSnapshot (store.State) |
IRootState.GetSliceState<T>(), GetSliceState<T>(key); (dev) store.GetSlice<T>(), GetSliceByKey, TryGetSlice, GetSliceKeys |
State.Get<T>(), State.Get(key), State.TryGet<T>(out …), State.Keys |
IRootStateSerializer, RootStateSerializer (Ducky) |
IStore.Json (DuckyJson), over the context passed to UseJson |
ISlice (Ducky) |
Slice, the non-generic base of Slice<TState> (IStore.Slices) |
DuckyComponent<TState> (Ducky.Blazor) |
same name and arity; State is one whole-slice selection |
DuckyComponent<TState>.Dispatcher.X(...) |
Store.X(...): the generated helpers work on IStore, and components have no Dispatcher property |
protected override void OnAfterSubscribed() |
OnInitialized() after the Select calls (2.0 doesn't seal it) |
Ducky.DependencyInjections (AddDuckyCore(DuckyOptions)), Ducky.Blazor.DependencyInjections (AddDucky(IConfiguration?, Action<DuckyOptions>?)), DuckyOptions |
AddDucky(d => …). Same name, incompatible signature, so the compiler reports CS1503; binding from the Ducky configuration section is removed |
DuckyOptions.AssemblyNames, implicit scan; (dev) ScanAssemblies |
AddDuckyGenerated_{Asm}(), generated per assembly |
AddDuckyBlazor, BlazorDuckyBuilder (dev) |
AddDucky(d => d.AddBlazor()) |
StoreInitialized (Ducky) |
same name, a plain record with no TypeKey; an Effect<StoreInitialized> does the initial load |
ReactiveEffect (Ducky), CustomOperators, ReactiveSelectorExtensions, StateActionPair<TState, TAction> |
install Ducky.Reactive: ReactiveEffect.Handle(Observable<object> actions, Observable<StateSnapshot> state), actions.OfActionType<T>() and R3's own operators. No tombstone: it would be ambiguous with Ducky.Reactive.ReactiveEffect for code importing both namespaces |
ObservableExtensions (FirstSync) |
store.State, or Selection<T>.Value |
ReactiveEffectTestHelper |
Ducky.Testing + R3's FakeTimeProvider |
ActionMeta, IFsaMeta<TMeta>, IFsaPayload<TPayload> (Ducky) |
properties of the plain action record, as for Fsa (DUCKYM006) |
IEntity<TKey> (Ducky) |
unchanged: EntityState<TKey, TEntity> keys entities by IEntity<TKey>.Id |
INormalizedStateCollectionMethods<TKey, TEntity, TState> (Ducky) |
the methods of EntityState<TKey, TEntity>, as for NormalizedState (DUCKYM007) |
MergeStrategy (Ducky) |
same name: FailIfDuplicate is unchanged, Overwrite becomes PreferIncoming, PreferExisting is new |
ValueCollection<T>, EnumerableExtensions (ToValueCollection) (Ducky) |
ImmutableArray<T> or ImmutableList<T>: change detection compares references, so value equality buys nothing |
StateChange<TState>, StateLoggerObserver<TState>, LoggerProvider, ConsoleFallbackLogger<T> (Ducky) |
ILogger from DI (Ducky logs through ILoggerFactory), ActivitySource and Meter; a Middleware with AfterReduce to observe each change |
IStoreEventPublisher, *EventArgs (dev) |
ILogger, ActivitySource, Meter |
DuckyException (Ducky) |
DuckyConfigurationException (its Errors carry DUCKY3xx codes) for configuration errors; failures while running are ReducerFailed and EffectFailed actions |
DuckyVersioning (Ducky) |
removed: read typeof(IStore).Assembly.GetName().Version |
IMiddleware (Ducky) |
Middleware. No tombstone: it would clash with Microsoft.AspNetCore.Http.IMiddleware, which Web SDK implicit usings import |
UseDefaultMiddlewares (dev) |
nothing |
EnablePersistence(...) (dev) |
Persist<T>(...) per slice |
EnableDevTools (dev) |
UseDevTools() guarded by IsDevelopment() |
EnableJsLogging (dev) |
removed: use DevTools and ILogger |
CrossTabSync (dev) |
o.SyncAcrossTabs = true |
WhenSliceChanges (dev) |
Select(selector, onChange, comparer) |
IExceptionHandler, DuckyErrorBoundary (dev) |
an effect on ReducerFailed or EffectFailed |
IsHydrated (dev) |
State.Get<PersistenceState>().Status |
StoreInitializer (dev) |
optional <DuckyInitializer> |
global using Ducky.Generators; |
using Ducky; |
global ActionDispatcher |
{Record}DispatchExtensions in the record's namespace |
[DuckyEffect], [DuckyReducer], [InitialState], [DuckyComponent] (dev) |
removed |
RouterStoreState, RouterReducers, RouterCancelAction, RouterErrorAction, RouterNavigatedAction, RouterNavigationAction, RouterRequestAction, RouterRequestAction.ActionPayload (Ducky.Blazor.Router) |
no 2.0 equivalent: removed. Keep routing out of the store and use NavigationManager |
Behaviour changes
These compile unchanged. Each comes with the test that pins it. Sections marked (dev) describe the behaviour of the unreleased 1.x dev branch, not 1.0.292.
Change detection compares references
A reducer that returns a new instance is a change, even when it equals the old one; returning the same instance is not. 1.x compared with Equals. DUCKY011 flags s with { } in a reducer.
[Fact]
public async Task ChangeDetection_EqualButNewRecord_IsAChange()
{
await using var store = TestStore.Create(ducky => ducky.AddSlice<Fixtures.TallySlice>());
var before = store.State;
await store.DispatchAsync(new Fixtures.Touch()); // returns `state with { }`: equal, but a new reference
store.State.Get<Fixtures.Tally>().ShouldBe(before.Get<Fixtures.Tally>());
store.State.Version.ShouldBe(before.Version + 1); // committed and notified: 1.x compared with Equals
await store.DispatchAsync(new Fixtures.Keep()); // returns the same instance
store.State.Version.ShouldBe(before.Version + 1); // no change
}Handlers match the exact action type
Reducers and effects see only the exact type they name: an Effect<TBase> no longer sees subtypes. DUCKY005 rejects an abstract type, an interface or object, which could never match.
[Fact]
public async Task HandlerMatching_Subtype_NotSeenByBaseTypeEffect()
{
await using var store = TestStore.Create(ducky => ducky.AddSlice<Fixtures.InboxSlice>().AddEffect<Fixtures.NotifyEffect>());
store.Dispatch(new Fixtures.UrgentNotify("fire")); // an Effect<Notify> no longer sees UrgentNotify : Notify
await store.Settled();
store.State.Get<Fixtures.Inbox>().Last.ShouldBeNull();
store.Dispatch(new Fixtures.Notify("mail"));
await store.Settled();
store.State.Get<Fixtures.Inbox>().Last.ShouldBe("mail");
}A synchronous Dispatch does not wait for the reduce
(dev) Dispatch reduces before it returns only when the calling thread becomes the drainer. While another thread drains, it queues the action and returns; a 1.x dev build blocked until that drain ended (1.0.292 already queued and returned). await DispatchAsync(...) completes once the action is reduced. The threading contract states the rules.
[Fact]
public async Task SyncDispatch_FromAnotherThreadWhileDraining_ReturnsBeforeReduced()
{
await using var store = TestStore.Create(ducky => ducky.AddSlice<CounterSlice>());
var draining = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var release = new ManualResetEventSlim();
using var selection = store.Select(s => s.Get<CounterState>().Value, value =>
{
if (value == 1)
{
draining.SetResult();
release.Wait(); // holds the drain: Increment(10) can't be reduced until released
}
});
var drainer = new Thread(() => store.Dispatch(new Increment(1)));
drainer.Start();
await draining.Task;
var returned = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var caller = new Thread(() =>
{
store.Dispatch(new Increment(10)); // another thread drains: the action is only queued
returned.SetResult(store.State.Get<CounterState>().Value);
});
try
{
caller.Start();
var seenOnReturn = await returned.Task.WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken);
seenOnReturn.ShouldBe(1); // a 1.x dev-build Dispatch blocked here until the drain ended
}
finally
{
release.Set();
drainer.Join();
caller.Join();
}
await store.WhenIdleAsync(TestContext.Current.CancellationToken);
store.State.Get<CounterState>().Value.ShouldBe(11); // reduced by the drainer; await DispatchAsync to read your writes
}Reducer exceptions become ReducerFailed
A throwing reducer is never rethrown to the dispatcher: the store dispatches ReducerFailed, and the action commits nothing, in any slice.
[Fact]
public async Task ReducerThrows_ReducerFailedDispatched_NothingCommitted()
{
await using var store = TestStore.Create(ducky => ducky.AddSlice<CounterSlice>().AddSlice<Fixtures.FragileSlice>());
var result = await store.DispatchAsync(new Increment(5)); // never rethrown
result.ShouldBe(DispatchResult.Failed);
store.State.Get<CounterState>().Value.ShouldBe(0); // CounterSlice's reduction is not committed either
var failure = store.Failures.ShouldHaveSingleItem().ShouldBeOfType<ReducerFailed>();
failure.Exception.Message.ShouldBe("boom");
}MaxReentrantDepth becomes MaxDispatchDepth
(dev) 1.x bounded the re-entrant queue length. MaxDispatchDepth (default 64) bounds the synchronous causal chain: an action dispatched while its parent is processed is one level deeper, and one above the limit is dropped with a ReducerFailed(DispatchLoopException).
[Fact]
public async Task MaxDispatchDepth_LimitsSynchronousCausalChain()
{
await using var store = TestStore.Create(ducky =>
{
ducky.MaxDispatchDepth = 3; // 1.x MaxReentrantDepth bounded the queue; this bounds the synchronous chain
ducky.AddSlice<Fixtures.PingSlice>().AddEffect<Fixtures.PingAgain>();
});
store.Dispatch(new Fixtures.Ping());
await store.Settled();
store.State.Get<Fixtures.Pings>().Count.ShouldBe(4); // depths 0 to 3
store.Failures.ShouldHaveSingleItem().ShouldBeOfType<ReducerFailed>().Exception.ShouldBeOfType<DispatchLoopException>();
}Subscribers and effects may run on a thread-pool thread
Whichever thread drains runs the reducers, the onChange callbacks and the effects' synchronous part, so after an effect's I/O that is a thread-pool thread. Marshal component work with InvokeAsync; DuckyComponent does so for its own re-render.
[Fact]
public async Task Subscriber_RunsOnTheDrainingThread()
{
var gate = new Fixtures.Gate();
await using var store = TestStore.Create(
ducky => ducky.AddSlice<CounterSlice>().AddEffect<Fixtures.LoadEffect>(),
services => services.AddSingleton(gate));
int? notifiedOn = null;
using var selection = store.Select(s => s.Get<CounterState>().Value, _ => notifiedOn = Environment.CurrentManagedThreadId);
store.Dispatch(new Fixtures.Load());
await gate.Started.Task;
var io = new Thread(gate.Release.SetResult); // stands for the thread pool thread that completes real I/O
io.Start();
io.Join();
notifiedOn.ShouldBe(io.ManagedThreadId); // not the renderer: marshal UI work with InvokeAsync
}Actions dispatched before init are buffered
An action dispatched while the store initializes (a middleware's InitializeAsync, persistence's restore) waits in the init buffer and is reduced once the store is ready.
[Fact]
public async Task DispatchBeforeInit_IsBuffered_ReducedOnceReady()
{
var gate = new Fixtures.Gate();
await using var provider = new ServiceCollection()
.AddSingleton(gate)
.AddDucky(ducky => ducky.AddSlice<CounterSlice>().Use<Fixtures.SlowInit>())
.BuildServiceProvider();
var store = provider.GetRequiredService<IStore>();
store.Dispatch(new Increment(3)); // starts init and waits in the init buffer
store.State.Get<CounterState>().Value.ShouldBe(0);
gate.Release.SetResult();
await store.InitializeAsync(TestContext.Current.CancellationToken);
store.State.Get<CounterState>().Value.ShouldBe(3);
}Persisted 1.x data is discarded
(dev) 2.0 persists a new envelope ({"v":…,"at":…,"s":…}) without assembly-qualified type names, and there is no 1.x reader. A stored 1.x value reads as not found (a Debug log, EventId 2030), so the slice starts from Initial, its load effect runs, and the next write replaces the value. Pinned by Persist_OneXFormat_Discarded in test/Ducky.Blazor.Tests/Persistence/EnvelopeTests.cs, over the 1.x RootStateSerializer and typed local-storage formats.
DevTools options are trimmed
(dev) Realtime, Latency, CollapseActions and the StackTrace* options are removed, and Trace is off by default.
[Fact]
public void DevToolsOptions_Trimmed_TraceOffByDefault()
{
typeof(DevToolsOptions).GetProperties().Select(property => property.Name).Order(StringComparer.Ordinal)
.ShouldBe(["ActionSanitizer", "Filter", "MaxAge", "Name", "StateSanitizer", "Trace", "TraceLimit"]);
new DevToolsOptions().Trace.ShouldBeFalse();
}UseJson is required for DevTools payloads, persistence and prerender
Ducky never serializes by reflection: DevTools payloads, persisted slices and prerender seeds go through the context passed to UseJson. A persisted or prerendered state type it lacks fails at startup with DUCKY306.
[Fact]
public async Task Persist_WithoutUseJson_FailsAtStartupWithDucky306()
{
await using var without = new ServiceCollection()
.AddDucky(ducky => ducky.AddSlice<CounterSlice>().Persist<CounterSlice>())
.BuildServiceProvider();
await using var scope = without.CreateAsyncScope();
Should.Throw<DuckyConfigurationException>(() => scope.ServiceProvider.GetRequiredService<IStore>())
.Errors.ShouldContain(error => error.Code == "DUCKY306");
await using var with = new ServiceCollection()
.AddDucky(ducky => ducky.UseJson(AppJson.Default).AddSlice<CounterSlice>().Persist<CounterSlice>())
.BuildServiceProvider();
await using var withScope = with.CreateAsyncScope();
withScope.ServiceProvider.GetRequiredService<IStore>().State.Get<CounterState>().Value.ShouldBe(0);
}