### Start Documentation Website Locally Source: https://github.com/jasperfx/wolverine/blob/main/README.md Execute this command to launch the local development server for the documentation website. Requires Node.js and dependencies to be installed. ```bash npm run docs ``` -------------------------------- ### Setup Host for Integration Testing Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/testing.md Configure and start a Wolverine host for integration testing. This includes setting up services and enabling Wolverine. ```csharp var hostBuilder = Host.CreateDefaultBuilder(); hostBuilder.ConfigureServices( services => { services.AddSingleton(); } ); hostBuilder.UseWolverine(); _host = await hostBuilder.StartAsync(); ``` -------------------------------- ### Example Output of `dotnet run -- help` Command Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/command-line.md This output shows the available command-line tools, such as `check-env`, `describe`, `resources`, and `wolverine-diagnostics`, along with instructions for getting specific command help. ```bash The available commands are: Alias Description ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ check-env Execute all environment checks against the application codegen Utilities for working with JasperFx.CodeGeneration and JasperFx.RuntimeCompiler describe Writes out a description of your running application to either the console or a file help List all the available commands resources Check, setup, or teardown stateful resources of this system run Start and run this .Net application storage Administer the Wolverine message storage wolverine-diagnostics Wolverine diagnostics tools for inspecting generated code and runtime behavior Use dotnet run -- ? [command name] or dotnet run -- help [command name] to see usage help about a specific command ``` -------------------------------- ### Start Testing Services with Docker Compose Source: https://github.com/jasperfx/wolverine/blob/main/README.md Use this command to start the necessary testing services for integration tests. Requires Docker to be installed locally. ```bash docker compose up -d ``` -------------------------------- ### Start a New Saga with Static Start Method (C#) Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/sagas.md Use a static `Start()` or `StartAsync()` handler method on the `Saga` type itself to initiate a new saga. This example shows how to start an `OrderSaga` and return related messages. ```cs // This method would be called when a StartOrder message arrives // to start a new Order public static (Order, OrderTimeout) Start(StartOrder order, ILogger logger) { logger.LogInformation("Got a new order with id {Id}", order.OrderId); // creating a timeout message for the saga return (new Order{Id = order.OrderId}, new OrderTimeout(order.OrderId)); } ``` -------------------------------- ### Example Log Output for Message Execution Start Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/logging.md This is an example of the log entry generated by Wolverine when the LogMessageStarting policy is enabled. ```text [09:41:00 INF] Starting to process () ``` -------------------------------- ### Enable Resource Setup on Wolverine Startup Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/transports/nats.md Ensures that all defined Wolverine messaging resources, including NATS streams and consumers, are set up when the application starts. ```csharp opts.Services.AddResourceSetupOnStartup(); ``` -------------------------------- ### Quick Start: Decorate Endpoint Class/Method Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/versioning.md Example of decorating an endpoint class and method with [ApiVersion] attribute for versioning. ```APIDOC ## Decorate Endpoint Class/Method ### Description Apply the `[ApiVersion]` attribute to your endpoint class or handler method to declare API versions. Method-level attributes take precedence over class-level attributes. ### Code Example ```csharp using Asp.Versioning; using Wolverine.Http; [ApiVersion("1.0")] public static class OrdersV1Endpoint { [WolverineGet("/orders", OperationId = "OrdersV1Endpoint.Get")] public static OrdersV1Response Get() => new (["order-a", "order-b"]); } public record OrdersV1Response(IReadOnlyList Orders); ``` ### Class-level Versioning ```csharp // Class-level — all methods in this class are v2. [ApiVersion("2.0")] public static class OrdersV2Endpoint { [WolverineGet("/orders")] public static OrdersV2Response Get() => new ("ok", ["v2-a", "v2-b"]); } ``` ``` -------------------------------- ### Wolverine Leader Election Setup (C#) Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/exclusive-node-processing.md Configures the necessary persistence layer (SQL Server in this example) and enables node agent support, which are prerequisites for Wolverine's leader election mechanism used in exclusive node processing. ```csharp opts.PersistMessagesWithSqlServer(connectionString) .EnableNodeAgentSupport(); opts.ListenToRabbitQueue("singleton-queue") .ExclusiveNodeWithParallelism(5); ``` -------------------------------- ### Resource Setup on Startup with Azure Service Bus Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/transports/azureservicebus/object-management.md Configure Wolverine to ensure all defined Azure Service Bus queues, topics, and subscriptions exist when the application starts. This requires adding `AddResourceSetupOnStartup()` to the Wolverine options. ```csharp using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => { opts.UseAzureServiceBus("some connection string"); // Make sure that all known resources like // the Azure Service Bus queues, topics, and subscriptions // configured for this application exist at application start up opts.Services.AddResourceSetupOnStartup(); }).StartAsync(); ``` -------------------------------- ### Install Node.js Dependencies for Documentation Source: https://github.com/jasperfx/wolverine/blob/main/README.md Run this command in the root of the documentation folder to install required Node.js packages. This is a prerequisite for running the documentation website locally. ```bash npm install ``` -------------------------------- ### Setup Wolverine Resources (Bash) Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/managing.md Executes the `resources setup` command to create Marten database objects and known Wolverine transport objects like RabbitMQ, Azure Service Bus, or AWS SQS queues. ```bash dotnet run -- resources setup ``` -------------------------------- ### Install WolverineFx.Mqtt NuGet Package Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/transports/mqtt.md Install the WolverineFx.Mqtt library to enable MQTT transport in your project. This package uses MQTTnet internally for broker communication. ```bash dotnet add package WolverineFx.Mqtt ``` -------------------------------- ### Start Local Pulsar Broker on Windows Source: https://github.com/jasperfx/wolverine/blob/main/src/Transports/Pulsar/Wolverine.Pulsar.Tests/README.md Use this command on Windows to build and start a local Pulsar broker. Docker is required. ```bash build pulsar ``` -------------------------------- ### Install Wolverine EF Core Nuget Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/efcore/index.md Install the `WolverineFx.EntityFrameworkCore` Nuget package to enable EF Core integration. ```bash dotnet add package WolverineFx.EntityFrameworkCore ``` -------------------------------- ### Complete Wolverine NATS and JetStream Configuration Example Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/transports/nats.md A comprehensive example demonstrating Wolverine's NATS integration, including auto-provisioning, JetStream configuration, defining work queue streams, listening to subjects with durability, and publishing messages. ```csharp using var host = await Host.CreateDefaultBuilder() .UseWolverine(opts => { opts.UseNats("nats://localhost:4222") .AutoProvision() .WithCredentials("user", "pass") .UseJetStream(js => { js.MaxDeliver = 5; js.AckWait = TimeSpan.FromSeconds(30); }) .DefineWorkQueueStream("ORDERS", s => s.EnableScheduledDelivery(), "orders.>"); // Listen to orders with JetStream durability opts.ListenToNatsSubject("orders.received") .UseJetStream("ORDERS", "order-processor") .Named("order-listener"); // Publish order events opts.PublishMessage() .ToNatsSubject("orders.created"); opts.PublishMessage() .ToNatsSubject("orders.shipped"); opts.Services.AddResourceSetupOnStartup(); }).StartAsync(); ``` -------------------------------- ### Full Example: Constructing a Persistent Pulsar URI Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/transports/pulsar.md Shows a complete C# example for generating a persistent Pulsar topic URI, including the necessary `using` directive for `Wolverine.Pulsar`. ```csharp using Wolverine.Pulsar; var uri = PulsarEndpointUri.PersistentTopic("public", "default", "orders"); ``` -------------------------------- ### Run Inventory Server Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/OrderChainWithGrpc/README.md Starts the downstream InventoryServer. This should be run first. ```sh dotnet run --project src/Samples/OrderChainWithGrpc/InventoryServer --framework net9.0 ``` -------------------------------- ### Start a saga from an HTTP endpoint Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/sagas.md Demonstrates starting a saga by returning it as part of a tuple from an HTTP endpoint method. ```csharp [WolverinePost("/reservation")] public static ( // The first return value would be written out as the HTTP response body ReservationBooked, // Because this subclasses from Saga, Wolverine will persist this entity // with saga persistence Reservation, // Other return values that trigger no special handling will be treated // as cascading messages ReservationTimeout) Post(StartReservation start) { return (new ReservationBooked(start.ReservationId, DateTimeOffset.UtcNow), new Reservation { Id = start.ReservationId }, new ReservationTimeout(start.ReservationId)); } ``` -------------------------------- ### Run RacerWithGrpc Server Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/RacerWithGrpc/README.md Starts the gRPC server component of the racer sample. ```sh dotnet run --project src/Samples/RacerWithGrpc/RacerServer --framework net9.0 ``` -------------------------------- ### Ship Order Handler Example Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/handlers/index.md This example demonstrates a compound handler for shipping an order. The `LoadAsync` method fetches necessary data, and the `Handle` method contains the business logic. The `Handle` method is synchronous and receives only the data it needs, making it easy to unit test. ```cs public static class ShipOrderHandler { // This would be called first public static async Task<(Order, Customer)> LoadAsync(ShipOrder command, IDocumentSession session) { var order = await session.LoadAsync(command.OrderId); if (order == null) { throw new MissingOrderException(command.OrderId); } var customer = await session.LoadAsync(command.CustomerId); return (order, customer!); } // By making this method completely synchronous and having it just receive the // data it needs to make determinations of what to do next, Wolverine makes this // business logic easy to unit test public static IEnumerable Handle(ShipOrder command, Order order, Customer customer) { // use the command data, plus the related Order & Customer data to // "decide" what action to take next yield return new MailOvernight(order.Id); } } ``` -------------------------------- ### RacerClient Output Example Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/RacerWithGrpc/README.md Sample console output showing the client receiving race positions. ```text RacerClient connecting to http://localhost:5004 Starting race — press Ctrl+C to stop. Racer-A position=1 speed= 150.5 km/h Racer-B position=1 speed= 196.8 km/h Racer-A position=2 speed= 150.5 km/h Racer-B position=1 speed= 196.8 km/h Racer-C position=2 speed= 157.8 km/h ... ``` -------------------------------- ### Run the Process Manager Sample Application Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/ProcessManagerViaHandlers/README.md Navigate to the sample's directory and run the application using dotnet. ```bash cd src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers dotnet run ``` -------------------------------- ### Add Resource Setup on Startup Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/marten/multi-tenancy.md Ensures that message storage and other necessary resources are set up in all tenant databases during application startup. ```csharp builder.Services.AddResourceSetupOnStartup(); ``` -------------------------------- ### Quick Start: Enable Versioning in MapWolverineEndpoints Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/versioning.md Configure Wolverine to use API versioning within the application setup. ```APIDOC ## Enable Versioning in MapWolverineEndpoints ### Description Configure Wolverine's endpoint mapping to enable API versioning. This involves calling `UseApiVersioning` within the `MapWolverineEndpoints` options. ### Code Example ```csharp app.MapWolverineEndpoints(opts => { opts.UseApiVersioning(v => { // All options are optional — the defaults work out of the box. v.UnversionedPolicy = UnversionedPolicy.PassThrough; }); }); ``` ``` -------------------------------- ### Run the Process Manager Sample Tests Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/ProcessManagerViaHandlers/README.md Navigate to the test project's directory and execute the tests using dotnet. ```bash cd src/Samples/ProcessManagerViaHandlers/ProcessManagerViaHandlers.Tests dotnet test ``` -------------------------------- ### Run Server and Client Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/GreeterWithGrpcErrors/README.md Commands to execute the server and client components of the GreeterWithGrpcErrors sample. ```sh dotnet run --project src/Samples/GreeterWithGrpcErrors/Server --framework net9.0 ``` ```sh dotnet run --project src/Samples/GreeterWithGrpcErrors/Client --framework net9.0 ``` -------------------------------- ### MVC ActionResult Example - Get Source: https://github.com/jasperfx/wolverine/blob/main/docs/tutorials/from-mvc.md Illustrates MVC's use of ActionResult for returning different response types, including NotFound and Ok. ```csharp [HttpGet("{id}")] public async Task> Get(int id) { var order = await _repo.FindAsync(id); if (order == null) return NotFound(); return Ok(order); } ``` -------------------------------- ### Bootstrapping Wolverine with HostApplicationBuilder and EF Core Transactions Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/configuration.md This example demonstrates bootstrapping Wolverine using `HostApplicationBuilder`, integrating with EF Core for SQL Server, and automatically applying transaction middleware. ```csharp var builder = Host.CreateApplicationBuilder(); builder.UseWolverine(opts => { var connectionString = builder.Configuration.GetConnectionString("database"); opts.Services.AddDbContextWithWolverineIntegration(x => { x.UseSqlServer(connectionString); }); // Add the auto transaction middleware attachment policy opts.Policies.AutoApplyTransactions(); }); using var host = builder.Build(); await host.StartAsync(); ``` -------------------------------- ### Configure Wolverine with OpenTelemetry and Honeycomb in C# Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/logging.md This example demonstrates setting up Wolverine with OpenTelemetry for both metrics and tracing, integrating with Honeycomb as the collector. It also shows how to configure service name, message logging, and auditing policies. ```csharp var host = Host.CreateDefaultBuilder(args) .UseWolverine((context, opts) => { opts.ServiceName = "Metrics"; // Open Telemetry *should* cover this anyway, but // if you want Wolverine to log a message for *beginning* // to execute a message, try this opts.Policies.LogMessageStarting(LogLevel.Debug); // For both Open Telemetry span tracing and the "log message starting..." // option above, add the AccountId as a tag for any command that implements // the IAccountCommand interface opts.Policies.ForMessagesOfType().Audit(x => x.AccountId); // Setting up metrics and Open Telemetry activity tracing // to Honeycomb var honeycombOptions = context.Configuration.GetHoneycombOptions(); honeycombOptions.MetricsDataset = "Wolverine:Metrics"; opts.Services.AddOpenTelemetry() // enable metrics .WithMetrics(x => { // Export metrics to Honeycomb x.AddHoneycomb(honeycombOptions); }) // enable Otel span tracing .WithTracing(x => { x.AddHoneycomb(honeycombOptions); x.AddSource("Wolverine"); }); }) .UseResourceSetupOnStartup() .Build(); await host.RunAsync(); ``` -------------------------------- ### Create a new ASP.Net Core Web API project Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/integration.md Use this command to initialize a new ASP.Net Core Web API project from the command line. ```bash dotnet new webapi ``` -------------------------------- ### HTTP Endpoint Using Custom 'now' Parameter Strategy in C# Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/endpoints.md This example demonstrates an HTTP GET endpoint that receives a `DateTimeOffset` parameter named 'now', which will be populated by the custom `NowParameterStrategy`. ```csharp [WolverineGet("/now")] public static string GetNow(DateTimeOffset now) // using the custom parameter strategy for "now" { return now.ToString(); } ``` -------------------------------- ### Run the Wolverine F# Marten Sample Application Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/WolverineMartenFSharpSample/README.md This command starts the required PostgreSQL database using Docker Compose and then executes the Wolverine F# Marten sample application. ```bash docker compose up -d # Postgres on :5433 dotnet run --project src/Samples/WolverineMartenFSharpSample --framework net9.0 ``` -------------------------------- ### Starting a New Event Stream with PolecatOps Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/polecat/operations.md Example of using PolecatOps.StartStream to initiate a new event stream for a given aggregate root and event data. This is typically used in event sourcing scenarios. ```csharp public static class TodoListEndpoint { [WolverinePost("/api/todo-lists")] public static (TodoCreationResponse, IStartStream) CreateTodoList( CreateTodoListRequest request ) { var listId = CombGuidIdGeneration.NewGuid(); var result = new TodoListCreated(listId, request.Title); var startStream = PolecatOps.StartStream(listId, result); return (new TodoCreationResponse(listId), startStream); } } ``` -------------------------------- ### SignalR Client Test Harness Setup - Bootstrapping Client Host Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/transports/signalr.md Demonstrates bootstrapping an IHost instance with the SignalR Client within a test harness to simulate browser client communication. ```csharp var host = await Host.CreateDefaultBuilder() ``` -------------------------------- ### Simulating File Change and Sending Message Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/testing.md Example of simulating a file change event and sending a FileAdded message using IMessageBus. This setup is for testing message publishing on file system events. ```cs public record FileAdded(string FileName); public class FileAddedHandler { public Task Handle( FileAdded message ) => Task.CompletedTask; } public class RandomFileChange { private readonly IMessageBus _messageBus; public RandomFileChange( IMessageBus messageBus ) => _messageBus = messageBus; public async Task SimulateRandomFileChange() { // Delay task with a random number of milliseconds // Here would be your FileSystemWatcher / IFileProvider await Task.Delay( TimeSpan.FromMilliseconds( new Random().Next(100, 1000) ) ); var randomFileName = Path.GetRandomFileName(); await _messageBus.SendAsync(new FileAdded(randomFileName)); } } public class When_message_is_sent : IAsyncLifetime { private IHost _host = null!; public async Task InitializeAsync() { ``` -------------------------------- ### Define a Saga with Start and Handle Methods in C# Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/sagas.md This example demonstrates a basic Wolverine Saga with StartAsync to initialize the saga and HandleAsync to process subsequent messages. The Id property is used for saga correlation. ```csharp public class OrderSaga : Saga { public Guid Id { get; set; } public Task StartAsync(StartOrder command) { Id = command.Id; return Task.CompletedTask; } public Task HandleAsync(CompleteOrder command) { MarkCompleted(); return Task.CompletedTask; } } ``` -------------------------------- ### Run Wolverine F# Sample with Docker Compose Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/WolverineFSharpSample/README.md Use these commands to start the required Postgres infrastructure via Docker Compose and then execute the Wolverine F# sample application. The sample provisions its own database and message store tables on startup. ```bash docker compose up -d # Postgres on :5433 dotnet run --project src/Samples/WolverineFSharpSample --framework net9.0 ``` -------------------------------- ### Coordinated Version Matrix Example Source: https://github.com/jasperfx/wolverine/blob/main/docs/blog/late-may-2026-critter-stack-week.md Illustrates the coordinated versioning strategy across JasperFx, Marten, Polecat, and Wolverine, showing how patch waves are synchronized. ```text JasperFx 2.2.1 ─┬─► Marten 9.3.x ├─► Polecat 4.2.x └─► Wolverine 6.2.x ``` -------------------------------- ### Describe Handler by Fully-Qualified Name Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/command-line.md Use this command to get a detailed report on a specific message handler, showing its assembly scanning status, type-level rules, and method convention satisfaction without starting the host. ```bash dotnet run -- wolverine-diagnostics describe-handlers MyApp.Orders.CreateOrderHandler ``` -------------------------------- ### Run Wolverine F# Marten Aggregate Sample Source: https://github.com/jasperfx/wolverine/blob/main/src/Samples/WolverineMartenAggregateFSharpSample/README.md Starts the necessary Docker Compose infrastructure for Postgres and then executes the Wolverine F# Marten aggregate sample application. ```bash docker compose up -d # Postgres on :5433 dotnet run --project src/Samples/WolverineMartenAggregateFSharpSample --framework net9.0 ``` -------------------------------- ### Getting Started with EF Core and Wolverine Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/efcore/index.md Configure Wolverine to use EF Core for transactional middleware, saga support, and message persistence. Ensure your DbContext options lifetime is set to Singleton for performance. This registers the DbContext and enables EF Core transactional middleware, saga support, and storage operations. ```csharp var builder = Host.CreateApplicationBuilder(); var connectionString = builder.Configuration.GetConnectionString("sqlserver")!; // Register a DbContext or multiple DbContext types as normal builder.Services.AddDbContext( x => x.UseSqlServer(connectionString), // This is actually a significant performance gain // for Wolverine's sake optionsLifetime:ServiceLifetime.Singleton); // Register Wolverine builder.UseWolverine(opts => { // You'll need to independently tell Wolverine where and how to // store messages as part of the transactional inbox/outbox opts.PersistMessagesWithSqlServer(connectionString); // Adding EF Core transactional middleware, saga support, // and EF Core support for Wolverine storage operations opts.UseEntityFrameworkCoreTransactions(); }); // Rest of your bootstrapping... ``` -------------------------------- ### Configure Wolverine to Build Storage on Startup (C#) Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/managing.md Use this option to automatically build any missing database schema objects for persistent storage when the application starts. ```cs // This is rebuilding the persistent storage database schema on startup builder.Host.UseResourceSetupOnStartup(); ``` -------------------------------- ### Configure Kafka Consumer Cold Start Offset (C#) Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/transports/kafka.md Sets the starting offset for a Kafka consumer group when no committed offset exists for a partition. BeginAtEarliest() starts from the topic's beginning, while BeginAtLatest() skips the backlog. ```csharp opts.ListenToKafkaTopic("orders").BeginAtEarliest(); // cold start from the beginning of the topic ``` ```csharp opts.ListenToKafkaTopic("orders").BeginAtLatest(); // cold start from the tail (skip the backlog) ``` -------------------------------- ### Install Wolverine Polecat Integration Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/polecat.md Command to install the necessary NuGet package for Polecat integration in Wolverine. ```bash dotnet add package WolverineFx.Http.Polecat ``` -------------------------------- ### Install WolverineFx.Http.Newtonsoft Package Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/json.md Install the WolverineFx.Http.Newtonsoft NuGet package to enable Newtonsoft.Json support for Wolverine HTTP. ```bash dotnet add package WolverineFx.Http.Newtonsoft ``` -------------------------------- ### Build Wolverine Full Solution in Release Mode Source: https://github.com/jasperfx/wolverine/blob/main/CLAUDE.md Use this command to build the full 'wolverine.slnx' solution in Release configuration, which is recommended before pushing changes to ensure compatibility with CI builds. ```bash dotnet build wolverine.slnx -c Release ``` -------------------------------- ### Implement a Sample Wolverine Extension in C# Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/extensions.md This example shows how to implement `IWolverineExtension` to add service registrations and alter serialization settings within `WolverineOptions`. ```csharp public class SampleExtension : IWolverineExtension { public void Configure(WolverineOptions options) { // Add service registrations options.Services.AddTransient(); // Alter settings within the application options .UseNewtonsoftForSerialization(settings => settings.TypeNameHandling = TypeNameHandling.None); } } ``` -------------------------------- ### List Database Resources for Marten Integration (Wolverine CLI) Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/managing.md Lists available database resources, including those for Marten and Wolverine, showing their DatabaseUri and SubjectUri. ```bash dotnet run -- db-list # ┌────────────────────────────────────────┬───────────────────────────┐ # │ DatabaseUri │ SubjectUri │ # ├────────────────────────────────────────┼───────────────────────────┤ # │ postgresql://localhost/postgres/orders │ marten://store/ │ # │ postgresql://localhost/postgres │ wolverine://messages/main │ # └────────────────────────────────────────┴───────────────────────────┘ ``` -------------------------------- ### SQLite Connection String Examples for Wolverine Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/sqlite.md Examples of file-based SQLite connection strings for Wolverine durability. In-memory SQLite is not supported. ```csharp // File-based database (recommended) opts.PersistMessagesWithSqlite("Data Source=wolverine.db"); ``` ```csharp // File-based database in an application data folder opts.PersistMessagesWithSqlite("Data Source=./data/wolverine.db"); ``` -------------------------------- ### Start Local Pulsar Broker on OSX/Linux Source: https://github.com/jasperfx/wolverine/blob/main/src/Transports/Pulsar/Wolverine.Pulsar.Tests/README.md Use this command on OSX or Linux to build and start a local Pulsar broker. Docker is required. ```bash ./build.sh pulsar ``` -------------------------------- ### Add ASP.Net Core Web API Project Source: https://github.com/jasperfx/wolverine/blob/main/docs/tutorials/cqrs-with-marten.md Use this command to initialize a new ASP.Net Core Web API project. ```bash dotnet add webapi ``` -------------------------------- ### Install WolverineFx.Http NuGet Package Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/dead-letter-storage.md Install the necessary NuGet package to enable Dead Letters REST API functionality in your WolverineFX application. ```bash dotnet add package WolverineFx.Http ``` -------------------------------- ### MVC Authorization Filter Example Source: https://github.com/jasperfx/wolverine/blob/main/docs/tutorials/middleware-migration.md An example of an MVC Authorization Filter that checks for an 'X-Api-Key' header and returns Unauthorized if it's missing or incorrect. ```csharp public class ApiKeyFilter : IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { if (!context.HttpContext.Request.Headers.TryGetValue("X-Api-Key", out var key) || key != "secret") { context.Result = new UnauthorizedResult(); } } } ``` -------------------------------- ### Wolverine Logging Middleware Example Source: https://github.com/jasperfx/wolverine/blob/main/docs/tutorials/middleware-migration.md Implement logging middleware by creating a static class with a 'Before' method. Dependencies are injected as parameters. ```csharp public static class LoggingMiddleware { public static void Before(HttpContext context, ILogger logger) { logger.LogInformation("Executing {Path}", context.Request.Path); } } ``` -------------------------------- ### Install WolverineFx.Http.Newtonsoft Package Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/migration.md Install this NuGet package to enable Newtonsoft.Json serialization for HTTP endpoints in Wolverine 6.0, as it's no longer part of the core `WolverineFx.Http` package. ```sh dotnet add package WolverineFx.Http.Newtonsoft ``` -------------------------------- ### Manually Load Marten Document in C# Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/marten.md Demonstrates loading a Marten Invoice document using IQuerySession and a route parameter, explicitly handling the 404 Not Found response. ```cs { [WolverineGet("/invoices/longhand/{id}")] [ProducesResponseType(404)] [ProducesResponseType(200, Type = typeof(Invoice))] public static async Task GetInvoice( Guid id, IQuerySession session, CancellationToken cancellationToken) { var invoice = await session.LoadAsync(id, cancellationToken); if (invoice == null) return Results.NotFound(); return Results.Ok(invoice); } ``` -------------------------------- ### Define a 'Hello, World' HTTP GET endpoint with WolverineFx.HTTP Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/http/integration.md This class defines a simple HTTP GET endpoint at the root path ('/') that returns 'Hello.' using the `[WolverineGet]` attribute. ```cs public class HelloEndpoint { [WolverineGet("/")] public string Get() => "Hello."; } ``` -------------------------------- ### Wolverine Host Configuration Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/migrating-to-wolverine.md This example shows how to configure Wolverine within the .NET Generic Host, including RabbitMQ transport, PostgreSQL persistence, and explicit message publishing and listening. ```csharp builder.Host.UseWolverine(opts => { opts.UseRabbitMq(r => r.HostName = "localhost").AutoProvision(); opts.PersistMessagesWithPostgresql(connectionString); opts.PublishMessage().ToRabbitQueue("sales-orders"); opts.ListenToRabbitQueue("sales-orders"); }); ``` -------------------------------- ### Start a Saga and Schedule a Timeout Message in C# Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/messaging/message-bus.md This handler demonstrates how to start a new saga instance and simultaneously schedule an OrderTimeout message, linking the saga's lifecycle with a delayed message. ```cs // This method would be called when a StartOrder message arrives // to start a new Order public static (Order, OrderTimeout) Start(StartOrder order, ILogger logger) { logger.LogInformation("Got a new order with id {Id}", order.OrderId); // creating a timeout message for the saga return (new Order{Id = order.OrderId}, new OrderTimeout(order.OrderId)); } ``` -------------------------------- ### MediatR Vertical Slice Architecture Example Source: https://github.com/jasperfx/wolverine/blob/main/docs/introduction/from-mediatr.md This example illustrates a common MediatR implementation for a 'Vertical Slice Architecture' endpoint, featuring a request, its handler, and an MVC controller that dispatches the request via IMediator. ```csharp public class AddToCartRequest : IRequest { public int ProductId { get; set; } public int Quantity { get; set; } } public class AddToCartHandler : IRequestHandler { private readonly ICartService _cartService; public AddToCartHandler(ICartService cartService) { _cartService = cartService; } public async Task Handle(AddToCartRequest request, CancellationToken cancellationToken) { // Logic to add the product to the cart using the cart service bool addToCartResult = await _cartService.AddToCart(request.ProductId, request.Quantity); bool isAddToCartSuccessful = addToCartResult; // Check if adding the product to the cart was successful. return Result.SuccessIf(isAddToCartSuccessful, "Failed to add the product to the cart."); // Return failure if adding to cart fails. } public class CartController : ControllerBase { private readonly IMediator _mediator; public CartController(IMediator mediator) { _mediator = mediator; } [HttpPost] public async Task AddToCart([FromBody] AddToCartRequest request) { var result = await _mediator.Send(request); if (result.IsSuccess) { return Ok("Product added to the cart successfully."); } else { return BadRequest(result.ErrorMessage); } } } ``` -------------------------------- ### Bootstrap Wolverine with Ancillary Marten Stores in C# Source: https://github.com/jasperfx/wolverine/blob/main/docs/guide/durability/marten/ancillary-stores.md Demonstrates how to configure a Wolverine host to integrate with multiple Marten document stores, including a default store, a named `IPlayerStore` with event subscriptions, and a multi-tenanted `IThingStore`. It sets a common message storage schema for Wolverine durability across all stores. ```csharp theHost = await Host.CreateDefaultBuilder() .UseWolverine(opts => { // THIS IS IMPORTANT FOR MODULAR MONOLITH USAGE! // This helps Wolverine out to always utilize the same envelope storage // for all modules for more efficient usage of resources opts.Durability.MessageStorageSchemaName = "wolverine"; opts.Services.AddMarten(Servers.PostgresConnectionString).IntegrateWithWolverine(); opts.Policies.AutoApplyTransactions(); opts.Durability.Mode = DurabilityMode.Solo; opts.Services.AddMartenStore(m => { m.Connection(Servers.PostgresConnectionString); m.DatabaseSchemaName = "players"; }) .IntegrateWithWolverine() // Add a subscription .SubscribeToEvents(new ColorsSubscription()) // Forward events to wolverine handlers .PublishEventsToWolverine("PlayerEvents", x => { x.PublishEvent(); }); // Look at that, it even works with Marten multi-tenancy through separate databases! opts.Services.AddMartenStore(m => { m.MultiTenantedDatabases(tenancy => { tenancy.AddSingleTenantDatabase(tenant1ConnectionString, "tenant1"); tenancy.AddSingleTenantDatabase(tenant2ConnectionString, "tenant2"); tenancy.AddSingleTenantDatabase(tenant3ConnectionString, "tenant3"); }); m.DatabaseSchemaName = "things"; }).IntegrateWithWolverine(x => { x.MainConnectionString = Servers.PostgresConnectionString; }); opts.Discovery.DisableConventionalDiscovery() .IncludeType(typeof(PlayerMessageHandler)); opts.Services.AddResourceSetupOnStartup(); }).StartAsync(); ```