Arbiter.Server 7.1.2

dotnet add package Arbiter.Server --version 7.1.2
                    
NuGet\Install-Package Arbiter.Server -Version 7.1.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Arbiter.Server" Version="7.1.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Arbiter.Server" Version="7.1.2" />
                    
Directory.Packages.props
<PackageReference Include="Arbiter.Server" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Arbiter.Server --version 7.1.2
                    
#r "nuget: Arbiter.Server, 7.1.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Arbiter.Server@7.1.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Arbiter.Server&version=7.1.2
                    
Install as a Cake Addin
#tool nuget:?package=Arbiter.Server&version=7.1.2
                    
Install as a Cake Tool

Arbiter

A powerful, lightweight, and extensible implementation of the Mediator pattern and Command Query Responsibility Segregation (CQRS) for .NET applications.

Arbiter is designed for building clean, modular architectures like Vertical Slice Architecture and CQRS. It provides a comprehensive suite of libraries that work together to simplify complex application patterns while maintaining high performance and flexibility.

Build Status License

Key Features

  • Clean Architecture: Perfect for Vertical Slice Architecture and CQRS patterns
  • High Performance: Minimal overhead with efficient mediator implementation
  • Extensible: Pipeline behaviors, custom handlers, and extensive customization options
  • Observable: Built-in OpenTelemetry support for tracing and metrics
  • Database Agnostic: Support for Entity Framework Core, MongoDB, and more
  • Web Ready: Minimal API endpoints and MVC controller support
  • Communication: Integrated email and SMS messaging capabilities
  • Blazor Ready: First-class Dispatcher support for Blazor Auto, Server Interactive, and WebAssembly render modes

Table of Contents

Quick Start

Get started with Arbiter in just a few steps:

1. Install the Core Package

dotnet add package Arbiter.Mediation

2. Define a Request and Handler

// Define your request
public class GetUserQuery : IRequest<User>
{
    public int UserId { get; set; }
}

// Implement the handler
public class GetUserHandler : IRequestHandler<GetUserQuery, User>
{
    public async ValueTask<User?> Handle(GetUserQuery request, CancellationToken cancellationToken)
    {
        // Your business logic here
        return await GetUserFromDatabase(request.UserId);
    }
}

3. Register Services

services.AddMediator();
services.AddTransient<IRequestHandler<GetUserQuery, User>, GetUserHandler>();

4. Use the Mediator

public class UserController : ControllerBase
{
    private readonly IMediator _mediator;

    public UserController(IMediator mediator) => _mediator = mediator;

    [HttpGet("{id}")]
    public async Task<User> GetUser(int id)
    {
        return await _mediator.Send(new GetUserQuery { UserId = id });
    }
}

Packages

Core Libraries Packages

Library Package Description
Arbiter.Mediation Arbiter.Mediation Lightweight and extensible implementation of the Mediator pattern
Arbiter.Queue Arbiter.Queue Background request queue for mediator commands
Arbiter.CommandQuery Arbiter.CommandQuery Base package for Commands, Queries and Behaviors
Arbiter.Mapping Arbiter.Mapping Source-generated, compile-time object mapping
Arbiter.Services Arbiter.Services Utility services for CSV, encryption, caching, and tokens
Arbiter.Communication Arbiter.Communication Message template communication for email and SMS services

Data Providers Packages

Library Package Description
Arbiter.CommandQuery.EntityFramework Arbiter.CommandQuery.EntityFramework Entity Framework Core handlers for the base Commands and Queries
Arbiter.CommandQuery.MongoDB Arbiter.CommandQuery.MongoDB MongoDB handlers for the base Commands and Queries

Web Integration Packages

Library Package Description
Arbiter.Server Arbiter.Server ASP.NET Core middleware, routing and diagnostics
Arbiter.CommandQuery.Endpoints Arbiter.CommandQuery.Endpoints Minimal API endpoints for base Commands and Queries
Arbiter.CommandQuery.Mvc Arbiter.CommandQuery.Mvc MVC Controllers for base Commands and Queries

Blazor Dispatcher Packages

Library Package Description
Arbiter.Dispatcher.Server Arbiter.Dispatcher.Server ASP.NET Core endpoint that receives dispatcher messages from Blazor WASM clients
Arbiter.Dispatcher.Client Arbiter.Dispatcher.Client Client-side dispatcher for Blazor: JSON/MessagePack (WASM) and ServerDispatcher
Arbiter.Components Arbiter.Components Blazor building blocks for list, view, and edit pages

Communication Providers Packages

Library Package Description
Arbiter.Communication.Azure Arbiter.Communication.Azure Communication implementation for Azure Communication Services
Arbiter.Communication.Graph Arbiter.Communication.Graph Communication implementation for Microsoft Graph email delivery
Arbiter.Communication.Twilio Arbiter.Communication.Twilio Communication implementation for SendGrid and Twilio

Core Libraries

Arbiter.Mediation

A lightweight and extensible implementation of the Mediator pattern for .NET applications, designed for clean, modular architectures like Vertical Slice Architecture and CQRS.

Mediation Features
  • Request/Response Pattern: Handle requests with typed responses using IRequest<TResponse> and IRequestHandler<TRequest, TResponse>
  • Notifications/Events: Publish events using INotification and INotificationHandler<TNotification>
  • Pipeline Behaviors: Middleware-like cross-cutting concerns using IPipelineBehavior<TRequest, TResponse>
  • Dependency Injection: Seamless integration with .NET's DI container
  • High Performance: Minimal allocations and efficient execution
  • OpenTelemetry Ready: Built-in observability support
Installation
dotnet add package Arbiter.Mediation
Basic Usage

1. Define Request and Response

public class Ping : IRequest<Pong>
{
    public string? Message { get; set; }
}

public class Pong
{
    public string? Message { get; set; }
}

2. Implement Handler

public class PingHandler : IRequestHandler<Ping, Pong>
{
    public async ValueTask<Pong?> Handle(
        Ping request,
        CancellationToken cancellationToken = default)
    {
        // Simulate async work
        await Task.Delay(100, cancellationToken);

        return new Pong { Message = $"{request.Message} Pong" };
    }
}

3. Define Pipeline Behavior (Optional)

public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;

    public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
    {
        _logger = logger;
    }

    public async ValueTask<TResponse> Handle(
        TRequest request,
        RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken = default)
    {
        _logger.LogInformation("Handling {RequestType}", typeof(TRequest).Name);
        
        var response = await next(cancellationToken);
        
        _logger.LogInformation("Handled {RequestType}", typeof(TRequest).Name);
        
        return response;
    }
}

4. Register Services

// Register Mediator services
services.AddMediator();

// Register handlers
services.AddTransient<IRequestHandler<Ping, Pong>, PingHandler>();

// Register pipeline behaviors (optional)
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));

5. Use in Controllers

[ApiController]
[Route("api/[controller]")]
public class PingController : ControllerBase
{
    private readonly IMediator _mediator;

    public PingController(IMediator mediator) => _mediator = mediator;

    [HttpGet]
    public async Task<ActionResult<Pong>> Get(
        [FromQuery] string? message = null,
        CancellationToken cancellationToken = default)
    {
        var request = new Ping { Message = message ?? "Hello" };
        var response = await _mediator.Send(request, cancellationToken);
        
        return Ok(response);
    }
}

5. OpenTelemetry Integration (Optional)

The mediator provides built-in support for OpenTelemetry tracing and metrics:

using Arbiter.Mediation;
using Arbiter.Messaging.ServiceBus;
using Arbiter.Messaging.WebPubSub;

services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddSource(
            MediatorTelemetry.SourceName,
            ServiceBusTelemetry.SourceName,
            WebPubSubTelemetry.SourceName)
        .AddAspNetCoreInstrumentation()
        .AddConsoleExporter()
    )
    .WithMetrics(metrics => metrics
        .AddMeter(MediatorTelemetry.MeterName)
        .AddAspNetCoreInstrumentation()
        .AddConsoleExporter()
    );

Arbiter.OpenTelemetry.Server registers these messaging sources automatically. Service Bus uses the Azure SDK's native transport propagation. Web PubSub logical-message propagation is opt-in because it uses a versioned JSON envelope; enable it with configureOptions: options => options.WithTraceContextPropagation() only when all publishers and consumers understand that wire format. Baggage and message bodies are not added to telemetry.

Arbiter.Queue

Background request queue for mediator commands. Queued work is represented as an IRequest<Unit> and processed through IMediator, so request handlers and pipeline behaviors continue to apply.

dotnet add package Arbiter.Queue
services.AddBackgroundQueue();
services.AddTransient<IRequestHandler<SendWelcomeEmail, Unit>, SendWelcomeEmailHandler>();

await backgroundQueue.Enqueue(new SendWelcomeEmail(userId), cancellationToken);

Arbiter.Messaging.ServiceBus also provides a durable Service Bus-backed IBackgroundQueue implementation through AddServiceBusBackgroundQueue(...). ServiceBusBackgroundQueue enqueues serialized mediator requests, and ServiceBusBackgroundService processes those requests from either the hosted AddServiceBusBackgroundProcessor(...) worker or an Azure Functions Service Bus trigger.

Arbiter.CommandQuery

A comprehensive Command Query Responsibility Segregation (CQRS) framework built on top of the mediator pattern.

CommandQuery Features
  • CQRS Implementation: Clear separation between commands and queries
  • Pre-built Operations: Common CRUD operations out of the box
  • Generic Handlers: Reusable handlers for typical data operations
  • Smart Behaviors: Hybrid caching, auditing, validation, and soft delete support
  • Source-Generated Mapping: Compile-time object mapping via Arbiter.Mapping with [GenerateMapper] attribute
  • Enhanced Querying: Powerful filter, sort, and pagination support with type-safe operators
  • Multi-tenancy Ready: Built-in tenant isolation support
  • Unified Query System: Single EntityQuery class handles both paged and non-paged scenarios
  • Flexible Filtering: Support for complex filter expressions with multiple operators and logic combinations
Package Installation
dotnet add package Arbiter.CommandQuery
Service Registration
services.AddCommandQuery();
Built-in Commands and Queries

The library provides several pre-built commands and queries for common operations:

Entity Queries:

  • EntityIdentifierQuery<TKey, TReadModel> - Get entity by ID
  • EntityIdentifiersQuery<TKey, TReadModel> - Get multiple entities by IDs
  • EntityPagedQuery<TReadModel> - Queries both paged and non-paged scenarios with filtering and sorting

Entity Commands:

  • EntityCreateCommand<TKey, TCreateModel, TReadModel> - Create new entities
  • EntityUpdateCommand<TKey, TUpdateModel, TReadModel> - Update existing entities (includes upsert)
  • EntityDeleteCommand<TKey, TReadModel> - Delete entities
Example Usage

Query by ID:

var query = new EntityIdentifierQuery<int, ProductReadModel>(principal, 123);
var result = await mediator.Send(query);

Query with Filtering and Sorting:

var filters = new List<EntityFilter>
{
    new EntityFilter { Name = "Status", Operator = FilterOperators.Equal, Value = "Active" },
    new EntityFilter { Name = "Price", Operator = FilterOperators.GreaterThan, Value = 10.00m }
};

var sorts = new List<EntitySort>
{
    new EntitySort { Name = "Name", Direction = SortDirections.Ascending }
};

var query = new EntityQuery
{
    Filter = new EntityFilter { Filters = filters },
    Sort = sorts
};

// no page or page size will return all matches
var command = new EntityPagedQuery<ProductReadModel>(principal, query);
var result = await mediator.Send(command);

Paginated Query:

var entityQuery = new EntityQuery
{
    Filter = new EntityFilter 
    { 
        Name = "Category", 
        Operator = FilterOperators.Equal, 
        Value = "Electronics" 
    },
    Sort = new List<EntitySort>
    {
        new EntitySort 
        { 
            Name = "CreatedDate", 
            Direction = SortDirections.Descending 
        }
    },
    Page = 1,
    PageSize = 20
};

var query = new EntityPagedQuery<ProductReadModel>(principal, entityQuery);
var result = await mediator.Send(query);

Update Command:

var updateModel = new ProductUpdateModel
{
    Name = "Updated Product",
    Description = "Updated description",
    Price = 29.99m
};

var command = new EntityUpdateCommand<int, ProductUpdateModel, ProductReadModel>(principal, 123, updateModel);
var result = await mediator.Send(command);
Advanced Filtering and Querying

Complex Filter Logic:

var complexEntityQuery = new EntityQuery
{
    Filter = new EntityFilter
    {
        Filters = new List<EntityFilter>
        {
            new EntityFilter 
            { 
                Name = "Category", 
                Operator = FilterOperators.In, 
                Value = new[] { "Electronics", "Computers" } 
            },
            new EntityFilter 
            { 
                Name = "Price", 
                Operator = FilterOperators.GreaterThanOrEqual, 
                Value = 100.00m 
            },
            new EntityFilter 
            { 
                Name = "Name", 
                Operator = FilterOperators.Contains, 
                Value = "Gaming" 
            }
        },
        Logic = FilterLogic.And
    },
    Sort = new List<EntitySort>
    {
        new EntitySort { Name = "Price", Direction = SortDirections.Descending },
        new EntitySort { Name = "Name", Direction = SortDirections.Ascending }
    }
};

var query = new EntityPagedQuery<ProductReadModel>(principal, complexEntityQuery);
var result = await mediator.Send(query);

Arbiter.Mapping

Source-generated, compile-time object mapping with support for custom property expressions and IQueryable projection.

Mapping Installation
dotnet add package Arbiter.Mapping
Mapping Features
  • Source-Generated: Roslyn incremental source generator emits mapping code at build time
  • Zero Reflection: No runtime reflection or expression compilation
  • AOT Compatible: Fully compatible with Native AOT
  • Auto Property Matching: Automatically maps properties with matching names and compatible types
  • Custom Expressions: Configure custom property mappings via ConfigureMapping
  • Query Projection: Built-in ProjectTo support for Entity Framework and other query providers
  • Record Support: Supports mapping to records, init properties, and primary constructors
Basic Usage

1. Define a Mapper

[GenerateMapper]
public partial class UserToUserDtoMapper : MapperProfile<User, UserDto>
{
    protected override void ConfigureMapping(MappingBuilder<User, UserDto> mapping)
    {
        mapping.Property(d => d.FullName).From(s => s.FirstName + " " + s.LastName);
        mapping.Property(d => d.Age).From(s => DateTime.Now.Year - s.BirthDate.Year);
        mapping.Property(d => d.DepartmentName).From(s => s.Department!.Name);
        mapping.Property(d => d.AddressCount).From(s => s.Addresses.Count());
    }
}

2. Register the Mapper

services.AddSingleton<IMapper<User, UserDto>, UserToUserDtoMapper>();
services.AddSingleton<IMapper, ServiceProviderMapper>();

3. Use the Mapper

public class UserService
{
    private readonly IMapper<User, UserDto> _userMapper;

    public UserService(IMapper<User, UserDto> userMapper) => _userMapper = userMapper;

    public UserDto GetUserDto(User user) => _userMapper.Map(user);
}

Arbiter.Services

Utility library providing common infrastructure services for .NET applications.

Services Installation
dotnet add package Arbiter.Services
Services Features
  • CSV Parsing: Read and write CSV data with flexible configuration
  • Encryption: Symmetric encryption and hashing utilities
  • Caching: Helpers for building cache keys and managing cache entries
  • Token Management: Secure token generation and validation
  • URL Building: Fluent API for constructing URLs with query parameters
  • Extension Methods: Common helpers in Arbiter.Services.Extensions for strings, claims, GUIDs (sequential SQL / Base62), dates, time zones, business days, cloning, and background tasks

Data Providers

Arbiter.CommandQuery.EntityFramework

Entity Framework Core integration providing ready-to-use handlers for all base commands and queries.

CommandQuery EntityFramework Installation
dotnet add package Arbiter.CommandQuery.EntityFramework
CommandQuery EntityFramework Features
  • Complete CRUD Operations: Pre-built handlers for all entity operations
  • Change Tracking: Automatic audit fields and soft delete support
  • Optimized Queries: Efficient EF Core query patterns
  • Transaction Support: Proper transaction management
  • Bulk Operations: Support for bulk insert/update operations
Setup
// Add Entity Framework Core services
services.AddDbContext<TrackerContext>(options =>
    options.UseSqlServer(connectionString)
);

// Register Command Query services
services.AddCommandQuery();

// Register source-generated mappers
services.AddSingleton<IMapper<Product, ProductReadModel>, ProductToReadModelMapper>();
services.AddSingleton<IMapper<ProductCreateModel, Product>, ProductCreateModelToProductMapper>();
services.AddSingleton<IMapper<ProductUpdateModel, Product>, ProductUpdateModelToProductMapper>();
services.AddSingleton<IMapper, ServiceProviderMapper>();

// Register Entity Framework handlers for each entity
services.AddEntityQueries<TrackerContext, Product, int, ProductReadModel>();
services.AddEntityCommands<TrackerContext, Product, int, ProductReadModel, ProductCreateModel, ProductUpdateModel>();

Arbiter.CommandQuery.MongoDB

MongoDB integration providing handlers for all base commands and queries with document database optimizations.

dotnet add package Arbiter.CommandQuery.MongoDB
MongoDB Setup
// Add MongoDB Repository services
services.AddMongoRepository("Tracker");
services.AddCommandQuery();

// Register source-generated mappers
services.AddSingleton<IMapper<Product, ProductReadModel>, ProductToReadModelMapper>();
services.AddSingleton<IMapper<ProductCreateModel, Product>, ProductCreateModelToProductMapper>();
services.AddSingleton<IMapper<ProductUpdateModel, Product>, ProductUpdateModelToProductMapper>();
services.AddSingleton<IMapper, ServiceProviderMapper>();

// Register MongoDB handlers for each entity
services.AddEntityQueries<IMongoEntityRepository<Product>, Product, string, ProductReadModel>();
services.AddEntityCommands<IMongoEntityRepository<Product>, Product, string, ProductReadModel, ProductCreateModel, ProductUpdateModel>();

Web Integration

Arbiter.Server

ASP.NET Core server infrastructure that depends only on the Microsoft.AspNetCore.App shared framework, so it can be used without Arbiter.CommandQuery:

  • IEndpointRoute and MapEndpointRoutes for modular Minimal API route registration
  • UseRequestLogging and UseClaimLogging middleware with logging scopes and activity tags for the user name, id, login provider and authentication method, plus any claims you include
  • AddDiagnosticRoutes for the claims-check, config-debugger, config-reload and cache-clear routes, secured by the localhost authorization policy, with configurable redaction of header, cookie and claim values
  • ProblemDetailsExtensions for consistent problem details error responses, with the status code and errors read from Exception.Data and exception details included only in Development unless ProblemDetailsExceptionOptions says otherwise
  • ForwardedHeadersOptionsSetup to configure the forwarded headers middleware, such as the client address header and trusted proxy networks, from the ForwardedHeaders configuration section
dotnet add package Arbiter.Server
Server Setup
using Arbiter.Server;

var builder = WebApplication.CreateBuilder(args);

// return exceptions as problem details, with the status code and errors read from Exception.Data
builder.Services.AddProblemDetails(ProblemDetailsExtensions.Configure);

builder.Services.AddDiagnosticRoutes();
builder.Services.AddSingleton<IEndpointRoute, StatusEndpoint>();

var app = builder.Build();

app.UseRequestLogging();
app.UseExceptionHandler(); // writes problem details for unhandled exceptions
app.MapEndpointRoutes(); // maps every registered IEndpointRoute under /api

app.Run();

public class StatusEndpoint : IEndpointRoute
{
    public void AddRoutes(IEndpointRouteBuilder endpoints)
        => endpoints.MapGet("status", () => TypedResults.Ok("ready"));
}

Any exception sets its problem details status code and validation errors through Exception.Data, with the ProblemDetailsExtensions.StatusCodeDataKey and ErrorsDataKey keys. DomainException from Arbiter.CommandQuery stores both, so it needs no registration:

throw new KeyNotFoundException("Item not found")
{
    Data = { [ProblemDetailsExtensions.StatusCodeDataKey] = StatusCodes.Status404NotFound },
};
Forwarded Headers

Behind a proxy such as Cloudflare, ForwardedHeadersOptionsSetup configures ForwardedHeadersOptions from the ForwardedHeaders configuration section, whose keys are the option property names. Only configured keys are applied, a configured list (KnownProxies, KnownIPNetworks, AllowedHosts) replaces the default rather than adding to it, and unknown keys or values that can't be parsed stop the app from starting:

builder.Services.ConfigureOptions<ForwardedHeadersOptionsSetup>();

var app = builder.Build();

app.UseForwardedHeaders(); // first, so logs and authorization see the client address
{
  "ForwardedHeaders": {
    "ForwardedHeaders": "XForwardedFor, XForwardedProto",
    "ForwardedForHeaderName": "CF-Connecting-IP",
    "KnownIPNetworks": [ "173.245.48.0/20", "2400:cb00::/32" ]
  }
}

Forwarded headers are trusted only from KnownProxies and KnownIPNetworks. Clearing both, or listing 0.0.0.0/0 and ::/0, trusts them from any peer, so any caller could claim any client address unless the origin accepts traffic from the proxy alone.

Arbiter.CommandQuery.Endpoints

Minimal API endpoints that automatically expose your commands and queries as REST APIs. Builds on Arbiter.Server, which it references.

dotnet add package Arbiter.CommandQuery.Endpoints
Endpoints Setup
using Arbiter.CommandQuery.Endpoints;
using Arbiter.Server;

var builder = WebApplication.CreateBuilder(args);

// Add endpoint services
builder.Services.AddEndpointRoutes();

// Optional: config-debugger, config-reload, health-check, claims-check and cache-clear routes
builder.Services.AddDiagnosticRoutes();

var app = builder.Build();

// Map endpoint routes (Arbiter.Server)
app.MapEndpointRoutes();

app.Run();

Custom Endpoint:

public class ProductEndpoint : EntityCommandEndpointBase<int, ProductReadModel, ProductReadModel, ProductCreateModel, ProductUpdateModel>
{
    public ProductEndpoint(ILoggerFactory loggerFactory)
        : base(loggerFactory, "Product")
    {
    }
}

// Register the endpoint
builder.Services.AddSingleton<IEndpointRoute, ProductEndpoint>();

Arbiter.CommandQuery.Mvc

MVC Controllers for base Commands and Queries with full ASP.NET Core integration. Builds on Arbiter.Server, which it references.

dotnet add package Arbiter.CommandQuery.Mvc
using Arbiter.Server;

// return exceptions as problem details; DomainException status codes and errors are read from Exception.Data
builder.Services.AddProblemDetails(ProblemDetailsExtensions.Configure);

var app = builder.Build();

app.UseExceptionHandler();

Blazor Dispatcher

The Dispatcher libraries provide a unified IDispatcher abstraction for sending commands and queries from Blazor components, with full support for Blazor Auto render mode. Components depend only on IDispatcher; the correct transport is wired at startup based on the render environment.

Render mode Implementation Transport
WebAssembly MessagePackDispatcher / JsonDispatcher HTTP POST to /api/dispatcher/send
Server Interactive ServerDispatcher Direct IMediator call (in-process)

Arbiter.Dispatcher.Server

Provides the DispatcherEndpoint—a single POST /api/dispatcher/send HTTP endpoint that deserializes incoming requests (JSON or MessagePack), resolves the target handler via IMediator, and streams the response back to the WASM client.

dotnet add package Arbiter.Dispatcher.Server
Server Setup
// Program.cs — Blazor host project
builder.Services.AddDispatcherService();

// ...

app.MapDispatcherService().RequireAuthorization();

MessagePack responses are not compressed by the serializer. AddDispatcherService adds application/x-msgpack to the response compression MIME types, so add AddResponseCompression and UseResponseCompression to the host to compress them, see Response compression.

Arbiter.Dispatcher.Client

Provides IDispatcher and its implementations, plus DispatcherDataService, ModelStateManager<TModel>, ModelStateLoader<TKey, TModel>, and ModelStateEditor<TKey, TReadModel, TUpdateModel> for Blazor component state management.

dotnet add package Arbiter.Dispatcher.Client
Client Setup — WebAssembly
// Program.cs — WASM client project
builder.Services
    .AddMessagePackDispatcher((sp, client) =>
    {
        client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
    });
Client Setup — Server Interactive
// Program.cs — Blazor host project
builder.Services.AddServerDispatcher();
Client Setup — Blazor Auto render mode

Register both dispatchers so each render environment resolves IDispatcher correctly:

// Host project: server-side rendering + serves WASM clients
builder.Services.AddServerDispatcher();
builder.Services.AddDispatcherService();

// WASM client project: WebAssembly rendering
builder.Services
    .AddMessagePackDispatcher((sp, client) =>
    {
        client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
    });
Detecting a new deployment

A WebAssembly client keeps running the version it was loaded with until the browser is refreshed. Opt in by chaining AddApplicationVersionHandler() on the dispatcher registration: the client then sends EnvironmentOptions.ApplicationVersion in the X-Client-Version header and the server returns its own in X-Server-Version, so the client detects a new deployment, even when the request fails. Add <ApplicationUpdateAlert /> from Arbiter.Components to the main layout to ask the user to refresh, see Detecting a new deployment.

builder.Services
    .AddMessagePackDispatcher((sp, client) => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
    .AddApplicationVersionHandler();
Sending commands and queries

Inject IDispatcher or the higher-level IDispatcherDataService into any component or service:

// Low-level: IDispatcher
var query = new EntityIdentifierQuery<int, UserReadModel>(principal, userId);
var user = await dispatcher.Send<EntityIdentifierQuery<int, UserReadModel>, UserReadModel>(
    query, cancellationToken);

// High-level: IDispatcherDataService
var user = await dataService.Get<int, UserReadModel>(userId);
var page = await dataService.Page<UserReadModel>(entityQuery);
var saved = await dataService.Save<int, UserUpdateModel, UserReadModel>(userId, updateModel);
Component state management

ModelStateEditor manages the full load–edit–save–delete lifecycle for a Blazor edit form:

@inject ModelStateEditor<int, UserReadModel, UserUpdateModel> Store
@implements IDisposable

protected override async Task OnInitializedAsync()
{
    Store.OnStateChanged += (_, _) => InvokeAsync(StateHasChanged);

    if (IsCreate)
        Store.New();
    else
        await Store.Load(Id);
}

// Store.IsBusy  — true while a load/save/delete is in progress
// Store.IsDirty — true when the model has unsaved changes
// Store.Model   — the editable update model bound to the form
// Store.Save()  / Store.Delete() / Store.Cancel()

public void Dispose() => Store.OnStateChanged -= HandleStateChanged;

Communication

Arbiter.Communication

A flexible message templating system for email and SMS communications with support for multiple providers.

dotnet add package Arbiter.Communication
Communication Providers

Azure Communication Services:

dotnet add package Arbiter.Communication.Azure

Microsoft Graph Email:

dotnet add package Arbiter.Communication.Graph

SendGrid and Twilio:

dotnet add package Arbiter.Communication.Twilio

Documentation

Samples

Explore practical examples in the samples directory:

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Debugging packages

Packages include portable PDBs alongside their assemblies so Blazor WebAssembly consumers receive symbols during package restore. The .NET SDK's built-in GitHub Source Link support maps source files to the exact repository commit; untracked generated sources are embedded in the PDBs.

To copy package PDBs into a Blazor WebAssembly app's debug output, add this property to the app's project file (the Entity Framework sample already enables it):

<PropertyGroup>
  <CopyDebugSymbolFilesFromPackages>true</CopyDebugSymbolFilesFromPackages>
</PropertyGroup>

Release builds also produce .snupkg files, which the tagged-release workflow publishes to NuGet.org's symbol server. GitHub Packages and feedz receive the regular packages with their included PDBs. To step into package code, enable Source Link support and disable Just My Code in your debugger; enable NuGet.org's symbol server when symbols aren't available locally.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

If you find this project useful, please consider:

  • Starring the repository
  • Reporting issues
  • Contributing improvements
  • Spreading the word

Change Log

Version 7.0

Version 7 targets .NET 10 and .NET 11, upgrades MessagePack to v4, and moves the ASP.NET Core infrastructure into the new Arbiter.Server package.

Migrating from Version 6.x

Upgrade checklist:

  1. Target net10.0 or net11.0.
  2. Upgrade every Arbiter package to 7.x at the same time.
  3. Deploy the Blazor WebAssembly client and the dispatcher server together. The MessagePack wire format changed, see MessagePack wire format.
  4. Drain Service Bus queues that carry MessagePack message bodies before v7 consumers start.
  5. Update namespaces and replace removed APIs, see Namespace and package moves and Removed APIs.
  6. Review Behavior changes, in particular the diagnostics authorization default and Entity Framework optimistic concurrency.
Target frameworks

All packages target net10.0 and net11.0. net8.0 and net9.0 are no longer supported.

MessagePack wire format

Arbiter uses MessagePack between the dispatcher client (Blazor WebAssembly) and the dispatcher server, and for Service Bus message bodies. The dispatcher is a closed system where the client and server ship together, so v7 does not keep wire compatibility with v6. v6 and v7 cannot exchange MessagePack payloads:

  • No LZ4 compression. v6 compressed payloads larger than 64 bytes with LZ4. v7 cannot read them and fails with MessagePackSerializationException: Unexpected or out-of-range MessagePack value (code 0xc7) reading map header (or 0xc8).
  • New format for object values. Values in object members, such as EntityFilter.Value, use the MessagePack typeless format. v6 wrote a custom [typeName, value] pair. v6 cannot read the v7 format, and v7 reads the v6 pair as an object[] without an error.
  • .NET formats for Guid, decimal, DateTime and DateTimeOffset. Guid and decimal are written as 16 byte binary, DateTime with DateTime.ToBinary and DateTimeOffset as ticks and offset, the formats of MessagePack's DotNetOptimizedFormatterFactory. They are smaller and faster than the cross-language string and timestamp formats, and the dispatcher client and server are both .NET. A MessagePack reader in another language does not read these values as GUIDs, decimals or timestamps.

What this means for a deployment:

  • A browser still running a cached v6 WebAssembly client gets errors from list and search calls until it reloads the application. Small requests, such as a lookup by id, may still succeed.
  • Service Bus messages written by v6 fail to deserialize in a v7 consumer and are dead-lettered. Replaying them on v7 fails again, so drain the queues with v6 consumers first.
  • Anything you persisted with MessagePackDefaults.DefaultSerializerOptions, such as cache entries or blobs, must be discarded and written again.
MessagePack payload size and compression

v7 payloads are not compressed, and are typically 2 to 3 times larger than v6 payloads for paged results. MessagePack v4 moved LZ4 and Zstandard to native libraries that have no prebuilt WebAssembly build, and the .NET Zstandard codec throws PlatformNotSupportedException in the browser, so compression cannot be part of the payload.

Use HTTP response compression instead. AddDispatcherService adds application/x-msgpack to the response compression MIME types, and AddMessagePackDispatcher and AddJsonDispatcher accept compressed responses outside the browser. The browser negotiates and decompresses responses natively. Enable the middleware in the host:

builder.Services.AddResponseCompression(options => options.EnableForHttps = true);
builder.Services.AddDispatcherService();

// ...

app.UseResponseCompression(); // before MapDispatcherService

With the default providers, a 500 row paged result went from 54 KB to 3.6 KB with Zstandard on .NET 11, or 6.6 KB with Brotli. See Response compression for providers, HTTPS considerations and opting out.

DateTime values

A DateTime now keeps its Kind. v6 converted a Local value to UTC and read every value as Utc.

Value sent v6 server receives v7, object member such as EntityFilter.Value v7, DateTime member such as Created
DateTimeKind.Utc same instant, Utc same instant, Utc same instant, Utc
DateTimeKind.Local same instant, converted to Utc same clock time, Local same instant, Local
DateTimeKind.Unspecified same clock time, Utc same clock time, Unspecified same clock time, Unspecified

A Local value in an object member, such as DateTime.Now or DateTime.Today in a filter sent from the browser, is read on the server as the same clock time in the server's time zone. When the browser and server are in different time zones, the filter selects a different range. Send UTC values in filters, for example DateTime.UtcNow or value.ToUniversalTime(), or use DateTimeOffset.

A Local value in a DateTime member is converted to the reader's time zone, so it keeps the instant. Code that expected Kind to be Utc after a round trip should call ToUniversalTime().

Init-only members in MessagePack models

When a payload does not contain a member, for example because it was written by an older version of the model, an init-only member is left at its default value (0, null) instead of its initializer:

[MessagePackObject(true)]
public partial class ProductQuery
{
    public int PageSize { get; init; } = 50;  // missing from the payload: 0
    public int PageIndex { get; set; } = 1;   // missing from the payload: 1
}

Payloads written by v7 always contain every member, so traffic between v7 applications using the same model is not affected. Use a set accessor where the initializer must apply to older payloads.

MessagePack options and custom serialization code
  • AddMessagePackOptions now takes a Func<MessagePackSerializerOptions, MessagePackSerializerOptions>. MessagePack v4 options are immutable, so return a modified copy. Options passed to configure replace any registered options, so the call can be made before or after AddDispatcherService or AddMessagePackDispatcher:

    // v6, the action could not change the immutable options
    services.AddMessagePackOptions(options => { });
    
    // v7
    services.AddMessagePackOptions(options => options with { MaxBufferedMessageSize = 128 * 1024 * 1024 });
    
  • CustomFormatterResolver and TypePreservingFormatter are removed. MessagePackDefaults exposes DefaultFormatterFactory, DefaultFormatterResolver and DefaultSerializerOptions, and CreateFormatterFactory to build the same chain with more allowed types, see Behavior changes. Nullable annotation and required member validation are turned off in the defaults, to match MessagePack v3.

  • Code that uses MessagePack v3 APIs directly must be updated: resolvers (CompositeResolver, StandardResolver, ContractlessStandardResolver) are replaced by formatter factories, options.WithResolver(...) by options with { Resolver = ... }, and WithCompression by the MessagePack.LZ4 package. MessagePack.Annotations is now a type-forwarding shim. See the migration section of the MessagePack v4 README.

  • [MessagePackObject] models need no changes.

Namespace and package moves

There are no type forwarders: update the using directives and rebuild any library that was compiled against v6.

Types v6 namespace v7 namespace (package)
Extensions for string, claims, Guid, clone, random, task, type and byte arrays, and ToDelimitedString Arbiter.CommandQuery.Extensions Arbiter.Services.Extensions (Arbiter.Services)
ClaimNames Arbiter.CommandQuery.Services Arbiter.Services (Arbiter.Services)
IEndpointRoute, MapEndpointRoutes, AddDiagnosticRoutes, DiagnosticsEndpoint, DiagnosticsEndpointOptions, UseRequestLogging, RequestLoggingOptions, RequestLoggingMiddleware, UseClaimLogging, ClaimLoggingMiddleware, ClaimResult, ClaimType, ClaimLoggingType, WithEntityMetadata Arbiter.CommandQuery.Endpoints Arbiter.Server (Arbiter.Server)
  • Arbiter.CommandQuery.Extensions still exists for QueryExtensions, ExceptionExtensions, PrincipalReaderExtensions and ToIdentifierList. With only that using, the moved extension methods no longer resolve: add using Arbiter.Services.Extensions;.
  • Arbiter.CommandQuery.Endpoints and Arbiter.CommandQuery.Mvc reference Arbiter.Server, so no new package reference is needed, only using Arbiter.Server;.
  • AddEndpointRoutes stays in Arbiter.CommandQuery.Endpoints, in the EndpointServiceExtensions class.
  • Arbiter.CommandQuery no longer references the Microsoft.Extensions.DependencyInjection, Microsoft.Extensions.Configuration and Microsoft.Extensions.Http packages. Projects that used them through Arbiter, for example BuildServiceProvider, ConfigurationBuilder or AddHttpClient in tests or console applications, must reference them directly.
Removed APIs
Removed Replacement
ProblemDetailsCustomizer ProblemDetailsExtensions in Arbiter.Server, with the same Configure, CustomizeProblemDetails and ToProblemDetails members
JsonExceptionMiddleware (Arbiter.CommandQuery.Mvc) builder.Services.AddProblemDetails(ProblemDetailsExtensions.Configure) and app.UseExceptionHandler()
Arbiter.Communication.Extensions (StringExtensions, HashExtensions) The string helpers are in Arbiter.Services.Extensions. ToXXHash3 has no replacement, use System.IO.Hashing.XxHash3
DiagnosticsEndpointOptions.HealthCheckEnabled, HealthCheckPolicy, ConfigureHealthCheckEndpoint The health-check route is added by AddEndpointRoutes and uses AuthorizationPolicy
CustomFormatterResolver, TypePreservingFormatter MessagePackDefaults.DefaultFormatterFactory
EntityPatchCommand and its handlers, AddEntityPatchCommand, AddEntityPatchBehaviors None. Use EntityUpdateCommand, or add your own command and handler

JSON Patch support is removed from every package:

  • EntityCommandEndpointBase no longer maps PATCH {id}, and EntityCommandControllerBase no longer has the Patch action or PatchCommand. PATCH requests to those routes now return 405 Method Not Allowed.
  • AddEntityCommands no longer registers a patch handler.
  • Arbiter no longer references SystemTextJsonPatch. Code that uses JsonPatchDocument must reference the package directly.
Signature changes
  • RequestLoggingOptions.IncludeRequestBody changed from bool to the RequestBodyLogging enum (Never, Always, OnError). Replace true with RequestBodyLogging.Always, including in configuration files.
  • ITemplateService.ApplyTemplate<TModel>(source, model) is now ApplyTemplate<TModel>(templateName, source, model). Parsed templates are cached by templateName for the lifetime of the service; pass null to parse without caching.
  • The BaseAddressResolver constructors take an IOptions<EnvironmentOptions>, registered by AddEnvironmentOptions, AddCommandQuery or AddEndpointRoutes.
  • The communication services take an IOptionsMonitor<EmailConfiguration> or IOptionsMonitor<SmsConfiguration> in place of IOptions<T>, followed by an optional optionsName for keyed services, so a configuration reload applies to the next message. This covers EmailTemplateService, SmsTemplateService, SmtpEmailDeliveryService, SendGridEmailDeliveryService, TwilioSmsDeliveryService, AzureEmailDeliveryService, AzureSmsDeliveryService and GraphEmailDeliverService. In tests, replace Options.Create(configuration) with an IOptionsMonitor<T>.
  • EmailTemplateService.Options is the current EmailConfiguration, not an IOptions<EmailConfiguration>. Replace Options.Value.FromName with Options.FromName.
  • The AddKeyedEmailDelivery and AddKeyedSmsDeliver factories receive the options monitor and the options name: replace (serviceProvider, options) => ... with (serviceProvider, options, optionsName) => ... and read options.Get(optionsName).
  • AddMessagePackOptions, see MessagePack options and custom serialization code.
Behavior changes
  • Diagnostics authorization. The default DiagnosticsEndpointOptions.AuthorizationPolicy is now Arbiter.LocalhostOnly, which allows only requests from the loopback address and does not require authentication. v6 required any authenticated user. Remote callers, such as monitoring tools, now get 403. To restore the v6 behavior:

    services.AddDiagnosticRoutes(options => options.AuthorizationPolicy = null);
    
  • health-check route. Mapped only when both AddEndpointRoutes and AddDiagnosticRoutes are called.

  • Environment name. EnvironmentOptions.EnvironmentName defaults to IHostEnvironment.EnvironmentName when a host environment is registered. A value set in configuration or code still wins.

  • User name claim. GetUserName reads preferred_username, upn, ClaimTypes.Upn, unique_name, ClaimTypes.Name, then sub. v6 read preferred_username, ClaimTypes.Name, then sub. Values such as CreatedBy and UpdatedBy can change for identity providers that send a upn or unique_name claim.

  • Entity Framework optimistic concurrency. EntityUpdateCommandHandler now checks the update model's RowVersion against the stored row, when the model implements ITrackConcurrency and the entity has a long RowVersion property configured as a concurrency token. If the row was changed or deleted after the caller loaded it, the update fails with a DomainException with status code 409 (Conflict), and the endpoints and the dispatcher return 409. v6 ignored the caller's RowVersion and overwrote the newer change. Send the RowVersion of the latest read model, such as the one returned by the previous save; a RowVersion of 0 skips the check. The Entity Framework command handlers throw this DomainException in place of DbUpdateConcurrencyException, which becomes its inner exception, so code that catches DbUpdateConcurrencyException must catch DomainException instead.

  • Problem details. The exception stack trace is included only in the Development environment by default. Change it with ProblemDetailsExceptionOptions.IncludeExceptionDetails.

  • Problem details from the dispatcher. For an exception that sets a status code, such as DomainException, the dispatcher endpoint returns the exception's own message as detail. v6 returned the message of its innermost exception. The title for status code 409 is Conflict.

  • FilterOperators.NotIn. Fixed. In v6 a NotIn filter threw a ParseException.

  • Types in MessagePack object members. A value in an object, interface or abstract member carries its type name, and the receiver creates that type. v7 creates only these types: primitives, string, decimal, Guid, date and time types, enums, arrays and framework collections of allowed types, types annotated with [MessagePackObject], and types declared in an assembly that references Arbiter.CommandQuery. Any other type fails with MessagePackSerializationException: Deserialization of type '...' is not allowed, and the dispatcher endpoint returns 400. v6 created any type named in the payload. To allow more types, such as a third party type in filter values:

    services.AddMessagePackOptions(options => options with
    {
        Resolver = new MessagePackFormatterResolver(MessagePackDefaults.CreateFormatterFactory(type => type == typeof(Instant)))
        {
            ValidateNullableAnnotations = false,
            ValidateRequiredMembers = false,
        },
    });
    
  • Dispatcher request types. The dispatcher endpoint returns 400 when the X-Message-Request-Type header names a type that is not a concrete IRequest, before it reads the body. Before, the body was read into the named type and the mediator then failed with 500.

Version 2.0

Major Breaking Changes and Improvements
Breaking Changes
  • Removed EntitySelectQuery: Replaced with enhanced EntityQuery that now supports both paged and non-paged results
  • Removed EntityUpsertCommand: Upsert functionality has been unified into EntityUpdateCommand with built-in upsert logic
  • Removed EntityContinuationQuery and EntityContinuationResult: Functionality now integrated into EntityQuery
  • Command/Query Reorganization:
    • Moved query classes (EntityIdentifierQuery, EntityIdentifiersQuery, EntityPagedQuery) to Commands namespace for better organization
    • Renamed base classes for consistency:
      • EntityIdentifierCommand → EntityIdentifierBase
      • EntityIdentifiersCommand → EntityIdentifiersBase
      • EntityModelCommand → EntityModelBase
    • Renamed filter, logic, and sort values for more consistent query building
      • EntityFilterOperators → FilterOperators
      • EntityFilterLogic → FilterLogic
      • EntitySortDirections → SortDirections
Architecture Improvements
  • Simplified Query System:

    • Consolidated multiple query types into a single, more powerful EntityQuery class
    • Removed redundant query handlers and behaviors
    • Enhanced filter and sort capabilities with better type safety
  • Enhanced Filtering:

    • Moved filter logic to dedicated Queries.FilterLogic and Queries.FilterOperators enums
    • Improved EntityFilterConverter with better validation and error handling
    • Enhanced LinqExpressionBuilder with more robust query building capabilities
  • Caching Simplification:

    • Removed DistributedCacheQueryBehavior and MemoryCacheQueryBehavior
    • Consolidated caching logic into HybridCacheQueryBehavior for better performance
    • Removed IDistributedCacheSerializer interface in favor of built-in serialization
Behavior Consolidation
  • Tenant Behaviors:

    • Removed TenantFilterBehaviorBase and TenantSelectQueryBehavior
    • Enhanced TenantPagedQueryBehavior to handle all tenant-related query filtering
  • Soft Delete Behaviors:

    • Removed DeletedFilterBehaviorBase and DeletedSelectQueryBehavior
    • Enhanced DeletedPagedQueryBehavior to handle all soft delete scenarios
  • Removed Legacy Behaviors:

    • TrackChangeCommandBehavior - functionality moved to handlers
    • Various base behavior classes that were no longer needed
Migration from Version 1.x

Updating Query Usage:

// Version 1.x - EntitySelectQuery (REMOVED)
var oldQuery = new EntitySelectQuery<ProductReadModel>(principal, filter, sort);

// Version 2.0 - Use EntityPagedQuery with EntityQuery instead
var entityQuery = new EntityQuery
{
    Filter = filter,
    Sort = sorts
};
var newQuery = new EntityPagedQuery<ProductReadModel>(principal, entityQuery);

Updating Filter Operators:

// Version 1.x - String operators (DEPRECATED)
var oldFilter = new EntityFilter 
{ 
    Name = "Status", 
    Operator = "eq", 
    Value = "Active" 
};

// Version 2.0 - Enum operators
var newFilter = new EntityFilter 
{ 
    Name = "Status", 
    Operator = FilterOperators.Equal, 
    Value = "Active" 
};

Updating Sort Directions:

// Version 1.x - String directions (DEPRECATED)
var oldSort = new EntitySort 
{ 
    Name = "Name", 
    Direction = "asc" 
};

// Version 2.0 - Enum directions
var newSort = new EntitySort 
{ 
    Name = "Name", 
    Direction = SortDirections.Ascending 
};

Upsert Operations:

// Version 1.x - Separate EntityUpsertCommand (REMOVED)
var oldUpsert = new EntityUpsertCommand<int, ProductUpsertModel, ProductReadModel>(principal, model);

// Version 2.0 - Use EntityUpdateCommand with upsert behavior
var newUpdate = new EntityUpdateCommand<int, ProductUpdateModel, ProductReadModel>(principal, id, model, true);
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.
  • net11.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Arbiter.Server:

Package Downloads
Arbiter.CommandQuery.Endpoints

Command Query Responsibility Segregation (CQRS) framework based on mediator pattern using Minimal API endpoints

Arbiter.CommandQuery.Mvc

Command Query Responsibility Segregation (CQRS) framework based on mediator pattern using ASP.NET MVC Controllers

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
7.1.2 0 12/4/2026
7.1.1 0 12/4/2026
7.1.0 0 12/4/2026
7.0.0 0 12/4/2026