Repository navigation
4.6. Payloads
A payload is a runtime-defined event contract identified by a registered, case-sensitive string name rather than a CLR event type. Its schema declares typed fields, including nested objects and collections. Payloads can replace DTO-style CLR events anywhere a behavior API accepts an event, and can also serve as Activity or Action data tokens.
Use a CLR event when the contract is compiled into an application type. Use a payload when producers and consumers need to share a named contract without sharing a DTO assembly, or when the contract is configured at runtime. Payloads are not an Activity-only feature.
Register payloads during Stateflows configuration with AddPayloads from Stateflows.Payloads. Payload names must be distinct from other payload names and registered CLR event names. Register definitions before the behavior definitions that reference them.
using System.ComponentModel.DataAnnotations;
using Stateflows;
using Stateflows.Common;
using Stateflows.Payloads;
services.AddStateflows(stateflows => stateflows
.AddPayloads(payloads => payloads
.AddPayload("orders.submitted", p => p
.AddField("orderId", FieldType.String, f =>
f.AddValidation(new RequiredAttribute()))
.AddField("quantity", FieldType.Int32, f =>
f.AddValidation(new RangeAttribute(1, 10)))
.AddField("hold", FieldType.Boolean)
.AddObjectField("address", address => address
.AddField("city", FieldType.String))
.AddCollectionField("tags", FieldType.String))
.AddPayload("orders.cancelled", p => p
.AddField("reason", FieldType.String)
.AddField("hold", FieldType.Boolean))
.AddPayload("orders.released", _ => { })
.AddPayload("orders.status", p => p
.AddField("status", FieldType.String))
.AddRequest("orders.query", "orders.status", p => p
.AddField("orderId", FieldType.String))));AddPayload registers a one-way payload. AddRequest registers a payload request whose response is either another registered payload (by response name) or a CLR event type (AddRequest<TResponse>). Field types are String, Boolean, Int32, Int64, Decimal, Double, Guid, DateTime, DateTimeOffset, TimeSpan, DateOnly, TimeOnly, Binary, and Enum. Enum fields declare allowed strings with AddEnumValues. Object and collection fields can be nested and validated; scalar collections can apply validation to each item.
Field names and payload names are case-sensitive. Missing fields are not automatically invalid; add an appropriate validation attribute, such as RequiredAttribute, when a value is mandatory. The normal Stateflows validation pipeline validates a payload against its registered schema before behavior processing. Invalid payloads are not processed.
Resolve IPayloadFactory from dependency injection. Use Create with a fluent builder or a field-value dictionary:
using Microsoft.Extensions.DependencyInjection;
using Stateflows.Common;
var payloadFactory = serviceProvider.GetRequiredService<IPayloadFactory>();
var submitted = payloadFactory.Create("orders.submitted", p => p
.Set("orderId", "A-1042")
.Set("quantity", 2)
.SetObject("address", address => address.Set("city", "London"))
.Set("tags", new[] { "priority", "gift" }));
var result = await behavior.SendAsync(submitted);Payload derives from PayloadValue. Read its registered name from Name and field data with Get<T>("fieldName"), TryGet<T>(...), or GetCollection<T>(...). Get<T> requires the exact runtime field type and throws if the field is missing or incompatible; nested objects are PayloadValue instances. Use ContainsField or TryGet for optional fields.
Payload names can be used anywhere a behavior accepts an event:
| Behavior surface | Registration | Callback receives |
|---|---|---|
| State Machine transitions |
AddPayloadTransition(["name"], ...), AddInternalPayloadTransition, AddElsePayloadTransition
|
Payload |
| State Machine deferrals | AddDeferredPayloadEvent(["name"]) |
Payload |
| Activity Accept Event nodes | AddAcceptPayloadEventAction(["name"], nodeName, ...) |
Payload |
| Action event metadata | AddConsumedPayloadEvent(["name"]) |
The incoming Payload is available as an input token |
| Entity mutations |
[Mutation("name")] or AddPayloadMutation(["name"], ...)
|
Payload |
| Initialization | State Machine/Activity AddPayloadInitializer, Entity [Initializer] or AddPayloadInitializer; an Action is implicitly initialized as it processes its first event |
Payload for named initialization; Action receives the incoming payload as an input token |
Payload-name-set builder APIs use IReadOnlyList<string> only, even when
registering one name. Use a one-element list such as ["orders.submitted"];
the previous shared-name overloads and single-string sugar have been removed.
CLR-typed builder methods such as AddTransition<TEvent> retain their existing
names. Payload-specific Use* selectors follow the same naming and list-only
rule (for example, UsePayloadTransition and UsePayloadFlow); selectors
configure an existing element through their callback rather than registering an
implementation class.
The payload-specific builder API now distinguishes name-based payload declarations from CLR-type declarations. Migrate payload-name overloads using the following names:
| Surface | Payload-specific methods |
|---|---|
| State Machine transitions |
AddPayloadTransition, AddInternalPayloadTransition, AddElsePayloadTransition, AddElseInternalPayloadTransition; selectors use UsePayloadTransition, UseInternalPayloadTransition, UseElsePayloadTransition, UseElseInternalPayloadTransition; inherited trigger changes use ChangePayloadTrigger
|
| State Machine deferrals and initialization |
AddDeferredPayloadEvent, UseDeferredPayloadEvent, AddPayloadInitializer
|
| Activity event acceptance |
AddAcceptPayloadEventAction, UseAcceptPayloadEventAction, ChangeAcceptedPayloadEvent
|
| Activity pins and decisions |
AddPayloadInputPin, UsePayloadInputPin, AddPayloadOutputPin, AddPayloadDecision, UsePayloadDecision
|
| Activity object flows |
AddPayloadFlow, UsePayloadFlow, AddElsePayloadFlow, AddPayloadTransformation
|
| Activity iterative/parallel nodes |
AddPayloadIterativeActivity, AddPayloadParallelActivity, UsePayloadIterativeActivity, UsePayloadParallelActivity
|
| Actions and agent event formatting |
AddConsumedPayloadEvent, AddConsumedPayloadToken, AddProducedPayloadToken; the agent formatter registration also takes a list of event names |
| Entities |
AddPayloadInitializer, AddPayloadMutation
|
These methods accept payload-name sets as lists only, including when there is
one name. This applies to the already payload-specific Action token methods as
well. Old shared-name payload overloads and single-name string sugar are
removed; no compatibility aliases remain. Use* methods select existing
elements and configure them through the supplied callback; they do not take an
implementation-class parameter. The change is limited to C# builder methods:
payload names, runtime behavior, JSON definition properties, and CLR-typed
builder methods are unchanged. Existing contextual methods such as
pin.AddFlow(target) remain unchanged when the payload-name context is already
selected by the containing builder.
Use a transition or deferral callback's Event property to access the payload:
.AddInitialState("Waiting", state => state
.AddPayloadTransition(["orders.submitted"], "Accepted", transition => transition
.AddGuard(c => c.Event.Get<int>("quantity") > 0))
.AddDeferredPayloadEvent(["orders.cancelled"]))
.AddState("Accepted");An Activity can accept a named payload while its event node is active:
.AddAcceptPayloadEventAction(
["orders.submitted"],
"ReceiveOrder",
async c =>
{
var orderId = c.Event.Get<string>("orderId");
c.Output(c.Event);
await audit.RecordAsync(orderId, c.CancellationToken);
},
node => node.AddPayloadFlow(["orders.submitted"], "ProcessOrder"))For initialization, State Machine and Activity AddPayloadInitializer overloads accept a list of names. Their predicate receives a context whose InitializationEvent is the payload and returns whether initialization is accepted. An Entity can register one or more names with [Initializer("name", ...)] on a method taking Payload, or use the named AddPayloadInitializer builder overload. Actions do not have a separate named-initializer registration: their first accepted payload event participates in the usual implicit Action initialization and is passed to the Action as an input token.
using System.Threading.Tasks;
.AddPayloadInitializer(["orders.created"], context =>
Task.FromResult(
!string.IsNullOrWhiteSpace(
context.InitializationEvent.Get<string>("orderId"))))This predicate shape works for State Machine and Activity initialization. The payload name must be registered; the initializer decides whether the instance may start from the supplied data.
Activity object flows can select payload tokens by a list of names. The payload
object itself moves between nodes; a payload flow matches its registered name,
not merely the CLR wrapper type. Use AddPayloadFlow for explicit payload-name
sets; transformations that produce named payloads use AddPayloadTransformation.
Payload input/output pins and decisions likewise use their AddPayload*
builder methods with a list of names. Payload pins are distinguished by their
declared name set, even though they all use the Payload CLR wrapper.
.AddAction("CreateOrder", async c =>
{
c.Output(payloadFactory.Create("orders.submitted", p => p
.Set("orderId", "A-1042")
.Set("quantity", 2)));
}, node => node.AddPayloadFlow(["orders.submitted"], "ProcessOrder"))
.AddAction("ProcessOrder", async c =>
{
var order = c.GetTokensOfType<Payload>().Single();
await processOrderAsync(order.Get<string>("orderId"), c.CancellationToken);
})For a standalone Action, declare consumed event names and payload token names
on its builder with list-only AddConsumedPayloadEvent(["name"]),
AddConsumedPayloadToken(["name"]), and
AddProducedPayloadToken(["name"]) methods. These declarations describe the
Action's supported events and token contracts; its execution context can read
and output Payload values like other token types. In an Activity,
AddPayloadFlow and the payload-aware pins and transformations declare the
names routed through the graph. Every referenced name must already be
registered.
See Activity Tokens, Data Flow, and Actions for typed token routing and execution contracts.
Entity mutation methods can use a payload parameter and list the names they handle:
using Stateflows.Common;
using Stateflows.Entities.Attributes;
public interface IOrder
{
[Field]
int Quantity { get; set; }
[Mutation("orders.adjusted")]
void Adjust(Payload mutation)
=> Quantity += mutation.Get<int>("delta");
[Initializer("orders.created")]
void Create(Payload initialization)
=> Quantity = initialization.Get<int>("quantity");
}In builder-based Entity definitions, use list-only AddPayloadMutation(["name"], ...)
and AddPayloadInitializer(["name"], ...); their contexts expose the received
value as MutationEvent and the initialization event respectively. An
attribute or builder may list multiple names for one handler; inspect
Payload.Name when its behavior differs by name. See Entity Mutations
and Entities.
AddRequest("request-name", "response-name", ...) declares a payload request/response contract using registered names. A response may instead be a CLR type with AddRequest<TResponse>. Resolve a payload request with the payload-aware RequestAsync extension and complete it with Respond:
var request = payloadFactory.Create("orders.query", p => p.Set("orderId", "A-1042"));
var result = await behavior.RequestAsync(request);
var status = result.Response.Get<string>("status");For a payload response, call request.Respond(responsePayload); for a CLR response, pass a value of the declared CLR type. Request/response delivery and correlation are described in Messaging Patterns.
The JSON extension defines payload schemas with JsonPayloadDefinition and registers them through AddPayloads. See JSON Definitions for the versioned schema, strict JSON decoding, and references from JSON behavior definitions.
Home page Support Code licensed under an MIT-style License. Documentation licensed under CC BY 4.0. © by Mikołaj Milewski, 2026