wolverine
Messaging code with Wolverine 6 (WolverineFx) in .NET 9 and 10 services. Use when code or a review touches UseWolverine, message handlers, IMessageBus, InvokeAsync, SendAsync, PublishAsync, cascading messages, the durable outbox and inbox on EF Core with PostgreSQL or SQL Server, AutoApplyTransactions, IDbContextOutbox, error policies and retries, the dead-letter queue, local queues, scheduled messages, code generation (TypeLoadMode, codegen write), tracked session tests, or the Wolverine RabbitMQ transport. Not for raw RabbitMQ.Client or EasyNetQ code and broker topology (dev-stack:rabbitmq), DbContext design (dev-stack:efcore), Wolverine.HTTP endpoints, Marten, or MassTransit and NServiceBus.
- License 许可
- MIT
- 最近更新
- 2026-11-13
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- wolverine
- metadata
- { "verified": "2026-10-27", "versions": "WolverineFx 6.56.0 (6.51.3 or later), JasperFx 2.96, RabbitMQ 4.3, EF Core 10, .NET 9 and 10" }
- description
- Messaging code with Wolverine 6 (WolverineFx) in .NET 9 and 10 services. Use when code or a review touches UseWolverine, message handlers, IMessageBus, InvokeAsync, SendAsync, PublishAsync, cascading messages, the durable outbox and inbox on EF Core with PostgreSQL or SQL Server, AutoApplyTransactions, IDbContextOutbox, error policies and retries, the dead-letter queue, local queues, scheduled messages, code generation (TypeLoadMode, codegen write), tracked session tests, or the Wolverine RabbitMQ transport. Not for raw RabbitMQ.Client or EasyNetQ code and broker topology (dev-stack:rabbitmq), DbContext design (dev-stack:efcore), Wolverine.HTTP endpoints, Marten, or MassTransit and NServiceBus.
02 资源文件 14
- 参考文档references/configuration.md9.8 KB
- 参考文档references/decisions.md5.3 KB
- 参考文档references/handlers.md5.2 KB
- 参考文档references/language.md4.7 KB
- 参考文档references/messaging-principles.md6.3 KB
- 参考文档references/review-checklist.md4.9 KB
- 参考文档references/sources.md7.1 KB
- 参考文档references/stack-rules.md7.6 KB
- 参考文档references/testing.md3.9 KB
- 参考文档references/wolverine5.md2.0 KB
- 参考文档rules.json7.0 KB
- 脚本scripts/convert.py2.9 KB
- 脚本scripts/doccheck.py28.8 KB
- 脚本scripts/stackcheck.py11.9 KB
03 SKILL.md 正文
Wolverine
Wolverine 6 as a mediator, a local queue, and a message bus with a durable outbox and inbox on EF Core. Also the settings of its RabbitMQ transport. Broker rules (queue types, dead-letter policies, names) are in dev-stack:rabbitmq. DbContext rules are in dev-stack:efcore. Wolverine.HTTP and Marten are out of scope: minimal API endpoints (API-01) call Wolverine through IDbContextOutbox<T> or InvokeAsync.
First
- Read
references/stack-rules.mdandreferences/messaging-principles.md. - Find the versions: the
WolverineFx*packages and the target framework in*.csproj,Directory.Build.props, orDirectory.Packages.props.- Wolverine 6 on .NET 9 or 10: use this file.
- Wolverine 5: read
references/wolverine5.md. Version 5 gets fixes for severe bugs only, and its end of life is October 2026. Tell the human. Upgrade only when the task asks for it. - .NET 8: Wolverine 6 does not support it. Stay on 5.x, or the raw client (
dev-stack:rabbitmq), and tell the human.
- Check
docs/dev-team/decisions.mdfor MSG-04 (Wolverine accepted), MSG-09 (outbox), and MSG-13 (code generation).
Done when you can name the Wolverine version, the target framework, the message store (PostgreSQL or SQL Server), and the transport.
Defaults for new code
Ask the human before you apply a default that has no accepted decision (stack rule 4). The full entries are in references/decisions.md. Contracts, names, queue types, idempotency, wire format, and tracing (MSG-05, MSG-06, MSG-07, MSG-10, MSG-11, MSG-12) are in dev-stack:rabbitmq.
| Area | Default | ID |
|---|---|---|
| Messaging library | Wolverine 6 for services that write to a database and publish. | MSG-04 |
| Mediator | No mediator. Wolverine InvokeAsync only when Wolverine is already in the service. |
MSG-02 |
| Unit of work | Policies.AutoApplyTransactions() with the EF Core integration. |
DATA-06 |
| Outbox and inbox | PersistMessagesWithPostgresql (or SQL Server), durable outbox on all senders, durable inbox on business listeners. |
MSG-09 |
| Retries | RetryWithCooldown(50ms, 250ms, 1s), then ScheduleRetry(10s, 1min) with jitter, then the error queue. Business and validation errors to the error queue at once. |
MSG-08 |
| Dead letters | One dead-letter queue per service, {service}.dlq, with CustomizeDeadLetterQueueing. |
MSG-06 |
| Code generation | TypeLoadMode.Static in production with codegen write in CI. Dynamic in development. WolverineFx.RuntimeCompilation in all builds. |
MSG-13 |
Existing code keeps its style (stack rule 3).
Rules
Host and code generation
TypeLoadMode.Dynamicis the default and needs the packageWolverineFx.RuntimeCompilation. Without it, the host does not start ("no IAssemblyGenerator (Roslyn) is registered").- For production, set
TypeLoadMode.Static, rundotnet run -- codegen writein CI, and commitInternal/Generated/(MSG-13). Static mode without the generated files does not start (MissingPreBuiltTypesException). The command starts the host, soProgram.csmust not connect to a database or broker beforeRunJasperFxCommands(args). - Set
opts.ApplicationAssembly = typeof(Program).Assembly. Then Wolverine looks for handlers in the app assembly, also when a test starts the app.
Registrations
- Register each
DbContextso that the code generator can see through it:opts.Services.AddDbContextWithWolverineIntegration<T>(...), orAddDbContext<T>(..., optionsLifetime: ServiceLifetime.Singleton). Wolverine 6 forbids service location by default. A plainAddDbContext<T>and a lambda registration (AddScoped<IFoo>(sp => ...)) then throwInvalidServiceLocationExceptionon the first message. - Use
AddScoped<IFoo, Foo>()for services that handlers inject. Useopts.CodeGeneration.AlwaysUseServiceLocationFor<T>()only for one opaque type, with a reason comment. Do not callopts.RestoreV5Defaults()or relaxServiceLocationPolicyto make the host start. - A typed
HttpClient(AddHttpClient<IFoo, Foo>(), with or without a configure lambda) is a factory registration too. A handler that injectsIFoothrowsInvalidServiceLocationExceptionon its first message. AddAlwaysUseServiceLocationFor<IFoo>()with a reason, or injectIHttpClientFactory(it works). A test factory that replacesIFoowith a singleton fake hides the error.
Handlers
- Write a handler as a public class whose name ends in
HandlerorConsumer. Give it aHandle,HandleAsync,Consume, orConsumeAsyncmethod. Prefer static classes and methods. Do not use MassTransit, NServiceBus, or MediatR interfaces. - Return nothing, a record, a tuple, or
OutgoingMessages. A method that returns a primitive (int,bool,string) is not a handler, andInvokeAsync<bool>then throwsIndeterminateRoutesException. - Return cascading messages from the handler. Do not inject
IMessageBusdeep into domain services, and do not wrap Wolverine in an ownIMessagePublisher. The generated code then commits the data and the outgoing messages together.
public static class ShipOrderHandler
{
// The returned message cascades: Wolverine sends it in the same transaction as the change.
public static async Task<OrderShipped> Handle(ShipOrder command, OrdersDbContext db, CancellationToken ct)
{
var order = await db.Orders.SingleAsync(o => o.Id == command.OrderId, ct);
if (order.Cancelled)
{
throw new OrderRuleException($"Order {order.Id} is cancelled."); // policy: error queue at once
}
order.Shipped = true; // AutoApplyTransactions calls SaveChangesAsync
return new OrderShipped(order.Id);
}
}
- Use
SendAsyncfor a command that must have a handler: it throws when no route exists.PublishAsyncis silent when nobody subscribes.
Outbox and inbox
- Configure all parts of the durable outbox (MSG-09):
PersistMessagesWithPostgresql(...)orPersistMessagesWithSqlServer(...).- The EF Core registration of rule 4 and
UseEntityFrameworkCoreTransactions(). Policies.AutoApplyTransactions().Policies.UseDurableOutboxOnAllSendingEndpoints()andPolicies.UseDurableInboxOnAllListeners().
- Outside a Wolverine handler (a minimal API endpoint, a
BackgroundService),AutoApplyTransactionsdoes nothing. InjectIDbContextOutbox<T>, calloutbox.PublishAsync(...), thenoutbox.SaveChangesAndFlushMessagesAsync(ct). Or send a command withbus.InvokeAsync(...)to a handler. ASaveChangesAsyncfollowed bybus.PublishAsyncis two transactions.
private static async Task<Created<OrderResponse>> CreateAsync(
CreateOrderRequest request, IDbContextOutbox<OrdersDbContext> outbox, TimeProvider time, CancellationToken ct)
{
var order = new Order(request.CustomerId!.Value, time.GetUtcNow());
outbox.DbContext.Orders.Add(order);
await outbox.PublishAsync(new OrderPlaced(order.Id, order.CustomerId, order.Total, order.PlacedAt));
await outbox.SaveChangesAndFlushMessagesAsync(ct); // one transaction, then Wolverine sends
return TypedResults.Created($"/orders/{order.Id}", order.ToResponse());
}
- The durable inbox removes duplicates by envelope ID for
Durability.KeepAfterMessageHandling(5 minutes by default). For business duplicates, use a natural key (MSG-10) orDeliveryOptions.DeduplicationId. KeepDurability.InboxStaleTimelonger than the longest handler with its retries.
RabbitMQ transport
-
Call
.UseQuorumQueues()and.ConfigureChannelCreation(o => { o.PublisherConfirmationsEnabled = true; o.PublisherConfirmationTrackingEnabled = true; }). The transport declares classic queues and turns confirms off by default. Wolverine deletes the outbox row when it writes the frame. So the outbox alone does not protect against a broker refusal (Wolverine documentation).Use WolverineFx 6.51.3 or later with the RabbitMQ transport and the durable inbox. Versions before 6.51.3 can lose messages after a broker outage (issue GH-5123). On quorum queues that a durable inbox reads, add
.DeliveryLimitForDurableQuorumQueues(-1)on the transport, or.DeliveryLimit(-1)on one listener. Each restart, reconnect, or shutdown returns the in-flight messages to the queue, and RabbitMQ 4 drops or dead-letters a message at its 21st return. The inbox owns the retries (MSG-08).Inlineand buffered listeners keep the broker limit of 20. Wolverine sets the limit only on a queue that it declares. For an existing queue, setdelivery-limit-1 in a broker policy instead (dev-stack:rabbitmq). -
Declare the topology:
.AutoProvision(), or exchanges and bindings that operations declares. Wolverine publishes withmandatory: false, so a message to an exchange without a binding is dropped. Mark a queue or exchange that another team owns.ExternallyOwned(). ElseAutoProvision()declares it with Wolverine's own arguments, the broker refuses withPRECONDITION_FAILED, and Wolverine retries the broker start. -
Choose the listener mode for each endpoint. The RabbitMQ listener default is
Inlinewith prefetch 100. Use the durable inbox for business messages.BufferedInMemoryacks at receipt and loses buffered messages in a crash. UseProcessInParallelWithNativeAcks()for parallel work without a database, andListenerCount(n)for parallelInlinework.
The full Program.cs is in references/configuration.md.
Failures
- Write an error policy for each exception type. Retry transient errors with cooldown, then a scheduled retry with jitter, then the error queue. Move validation and business errors to the error queue at once, or
Discard()them on purpose (MSG-08). Without a policy, Wolverine runs a failing message 3 times. - Do not catch and log an exception in a handler. Wolverine then sees a success and acks the message.
Contracts
- Pin each contract name with
[MessageIdentity("orders.order-placed", Version = 1)]. For a breaking change, add a new version type that implementsIForwardsTo<TNew>on the old one, and registeropts.RegisterMessageForwarder<TOld, TNew>(). Wolverine 6 no longer finds forwarders by itself (MSG-05).
Tests
- Test with tracked sessions:
host.TrackActivity().Timeout(30.Seconds()).InvokeMessageAndWaitAsync(message), then assert onsession.Sent,session.MovedToErrorQueue, orsession.AllRecordsInOrder(...). Get the host withfactory.Services.GetRequiredService<IHost>(). Do not useTask.Delay. A test of an error policy usesSendMessageAndWaitAsync:InvokeMessageAndWaitAsyncruns inline, so it passes with any policy. - In tests, call
services.DisableAllExternalWolverineTransports()andservices.RunWolverineInSoloMode(). WhenProgram.csends withRunJasperFxCommands(args), setJasperFxEnvironment.AutoStartHost = true(namespaceJasperFx.CommandLine) before you create theWebApplicationFactory. Without it, the factory fails with "The server has not been started". Detail:references/testing.md.
Review
Wolverine 6 defects build and pass the tests, and show only in production. In a review, look for them across files:
- For each new or changed handler, find the registration of each parameter in
Program.cs(rules 4 to 6). Also read the test factory: a fake there hides the production registration. - When a handler moves to a new message type, search for the old type. Look for an
IForwardsTo<T>withoutRegisterMessageForwarder(rule 19), and for tests that now send only the new type. - When production uses
TypeLoadMode.Static, a change to a handler must also changeInternal/Generated/. A deleted or stale folder passes the tests (Development usesDynamic) and stops the production start (rule 2).
Never write
| Wrong | Correct |
|---|---|
builder.Services.AddDbContext<OrdersDbContext>(o => ...) with Wolverine handlers |
opts.Services.AddDbContextWithWolverineIntegration<OrdersDbContext>(o => ...) |
public static bool Handle(CheckStock m) and InvokeAsync<bool>(...) |
public static StockResult Handle(CheckStock m) with record StockResult(bool InStock) |
class OrderPlacedConsumer : IConsumer<OrderPlaced> with ConsumeContext<T> |
public static class OrderPlacedHandler { public static void Handle(OrderPlaced message, ...) } |
await db.SaveChangesAsync(ct); await bus.PublishAsync(evt); in an endpoint |
IDbContextOutbox<T>: PublishAsync, then SaveChangesAndFlushMessagesAsync(ct) |
opts.UseRabbitMq(uri).AutoProvision(); and nothing else |
.UseQuorumQueues().DeliveryLimitForDurableQuorumQueues(-1).ConfigureChannelCreation(o => { both confirm flags }).AutoProvision() |
x.Production.GeneratedCodeMode = TypeLoadMode.Dynamic |
TypeLoadMode.Static and codegen write in CI |
A handler that injects ICarrierClient from AddHttpClient<ICarrierClient, HttpCarrierClient>(...) |
opts.CodeGeneration.AlwaysUseServiceLocationFor<ICarrierClient>() with a reason |
opts.RestoreV5Defaults() to make the host start |
Fix the registrations (rule 4), or AlwaysUseServiceLocationFor<T>() for one type with a reason |
opts.OnException<Exception>().RetryWithCooldown(...) for all errors |
One policy per exception type. Business errors: MoveToErrorQueue() |
try { ... } catch (Exception ex) { logger.LogError(ex, ...); } in a handler |
Let the exception reach the error policy |
.UseNativeAck() (does not exist) |
.ProcessInParallelWithNativeAcks() |
opts.UseNewtonsoftForSerialization() in new code |
Keep System.Text.Json (the default) |
await Task.Delay(2000) to wait for a handler |
host.TrackActivity().Timeout(...).InvokeMessageAndWaitAsync(...) |
Check
-
Build with the analyzers as errors:
dotnet build -warnaserrorPass:
Build succeededwith 0 warnings. -
Start the host once:
dotnet run, or a test withWebApplicationFactory. Pass: noInvalidServiceLocationException, noIAssemblyGeneratorerror. These errors come at startup or on the first message, not at build time. -
In CI, check the generated code:
dotnet run --project <app> -- codegen write git diff --exit-code -- '**/Internal/Generated/**'Pass: no diff.
-
Run the rules of this skill:
python3 <skill folder>/scripts/stackcheck.py --root <repo>Pass: 0 errors. For each warning, fix it or add
// stackcheck: ignore <RULE-ID> <reason>.
Review checklist
The full list is in references/review-checklist.md.
- Each
DbContextthat handlers inject is registered with the Wolverine integration oroptionsLifetime: Singleton. Each typedHttpClientor factory registration that a handler injects hasAlwaysUseServiceLocationFor<T>(). tool (WOLV-DBCONTEXT-OPTIONS, WOLV-TYPED-HTTPCLIENT), judge - No
RestoreV5Defaults(). tool (WOLV-RESTORE-V5) - Endpoints and background services use
IDbContextOutbox<T>orInvokeAsync. NoSaveChangesAsyncfollowed byPublishAsync. judge - The durable outbox has all its parts (rule 11). judge
- The RabbitMQ transport has
UseQuorumQueues()and both confirm flags, and the topology is declared. WolverineFx is 6.51.3 or later, and quorum queues of a durable inbox have delivery limit -1. Queues of another team areExternallyOwned(). judge - Handlers return records, tuples, or
OutgoingMessages, never a primitive. judge - Handlers do not catch and log exceptions. judge
- Error policies exist for each exception type. Business errors go to the error queue at once. judge
- No
IMessageBusin domain services. Messages cascade from handlers. judge - No MassTransit, NServiceBus, or MediatR interfaces. tool (WOLV-FOREIGN-IDIOM)
- Production uses
TypeLoadMode.Static, CI runscodegen write, andInternal/Generated/changes with each changed handler. tool (WOLV-DYNAMIC-PROD), judge - Contracts have
[MessageIdentity]. EachIForwardsTo<T>hasRegisterMessageForwarder, and a test still sends the old version. judge - Tests use tracked sessions, not
Task.Delay. Tests of error policies useSendMessageAndWaitAsync. tool (WOLV-TEST-DELAY), judge
Report
End with the report of stack rule 8 (references/stack-rules.md): the same headings in the same order on each run.
References
references/messaging-principles.md: read first. The principles that each message flow follows.references/decisions.md: read before new code needs MSG-02, MSG-04, MSG-08, MSG-09, or MSG-13.references/configuration.md: read when you write or reviewUseWolverine: the fullProgram.cs, the transport, the listener modes, and the durability settings.references/handlers.md: read when you write a handler, a cascading message, a scheduled message, or a message forwarder.references/testing.md: read before you write a test for a handler or a message flow.references/wolverine5.md: read only when the project uses Wolverine 5.references/review-checklist.md: read for a full review.references/sources.md: the primary sources and the credits.references/stack-rules.mdandreferences/language.md: the common rules and the output language.scripts/stackcheck.py: the rule check of this skill.
04 同仓库更多 Skills
web-accessibility
Web accessibility to WCAG 2.2 AA - a checklist for the design, the tool checks (axe-core, the Tab walk, reduced motion), and the manual checks that no tool does (screen reader, zoom, status messages) - with the EAA and EN 301 549 status. Use when a design, mockup, or built feature must be checked for accessibility, when a review must cover keyboard and screen reader use, when the user asks about focus, a focus trap, contrast, or a screen reader on a page, or when the user asks which accessibility rules apply.
ux-states
State inventory for each screen - default, empty, loading, partial, error, success, disabled, overflow, offline, and the business states (no permission, stale data, locked by another user, waiting on an external system, bulk result with failures, read only) - with what the user sees, can do, and how the user recovers. Use when a screen or flow needs its states designed or checked, or when a design shows only the happy path.
ux-setup
Set up a project for UX work - finds the design tools, the design-system source, the brand files, the languages, and the run command, asks the human one round of questions, and writes the "## Design" section of .claude/rules/delivery.md that the ux-design commands and the ux-designer agent read. Moves an older "## Design" section out of CLAUDE.md. Use when /setup, /ux-design, or /ux-review needs the design facts, when the ux-designer agent returns NEEDS_HUMAN because the "## Design" section is missing, or when the user wants to set up or change the design tools of a project.
ux-review
UX review of a built feature against its approved design - Playwright walks each flow and state at 390, 820, and 1440 px, axe-core and the tell checks run on each state, and each heuristic gets a verdict - with findings by owner, severity, and origin, and a verdict in ux-review.md in the work folder of the item. Use when a built feature or screen must be checked against its design, mockups, or prototype, in each state or at each screen size, when built screens need findings by severity, when the build of an item with a UX design is done, or when existing screens need a UX audit.
ux-prototype
Clickable prototype of a designed story in the proto-shell standard, with variants for an A/B test, all states in scope, three sizes, and a test plan with tasks. Use when a design or mockups exist and the team must test the flow or compare variants with users before the build.
ux-practice
The method of the ux-designer agent for the UX design of a story, a feature, or a screen - Double Diamond phases, a design spec with a source for each decision, the UX decision log, evidence tags, severity, and the modes light, full, and new-direction. Preloaded by the ux-designer agent. Use when the ux-designer agent or another UX skill names this method. For the design of an item, a person starts ux-design:ux-design.