Arbiter.Server
7.1.2
dotnet add package Arbiter.Server --version 7.1.2
NuGet\Install-Package Arbiter.Server -Version 7.1.2
<PackageReference Include="Arbiter.Server" Version="7.1.2" />
<PackageVersion Include="Arbiter.Server" Version="7.1.2" />
<PackageReference Include="Arbiter.Server" />
paket add Arbiter.Server --version 7.1.2
#r "nuget: Arbiter.Server, 7.1.2"
#:package Arbiter.Server@7.1.2
#addin nuget:?package=Arbiter.Server&version=7.1.2
#tool nuget:?package=Arbiter.Server&version=7.1.2
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.
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
- Packages
- Core Libraries
- Data Providers
- Web Integration
- Blazor Dispatcher
- Documentation
- Samples
- Contributing
- License
- Change Log
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 | Lightweight and extensible implementation of the Mediator pattern | |
| Arbiter.Queue | Background request queue for mediator commands | |
| Arbiter.CommandQuery | Base package for Commands, Queries and Behaviors | |
| Arbiter.Mapping | Source-generated, compile-time object mapping | |
| Arbiter.Services | Utility services for CSV, encryption, caching, and tokens | |
| Arbiter.Communication | Message template communication for email and SMS services |
Data Providers Packages
| Library | Package | Description |
|---|---|---|
| Arbiter.CommandQuery.EntityFramework | Entity Framework Core handlers for the base Commands and Queries | |
| Arbiter.CommandQuery.MongoDB | MongoDB handlers for the base Commands and Queries |
Web Integration Packages
| Library | Package | Description |
|---|---|---|
| Arbiter.Server | ASP.NET Core middleware, routing and diagnostics | |
| Arbiter.CommandQuery.Endpoints | Minimal API endpoints for base Commands and Queries | |
| Arbiter.CommandQuery.Mvc | MVC Controllers for base Commands and Queries |
Blazor Dispatcher Packages
| Library | Package | Description |
|---|---|---|
| Arbiter.Dispatcher.Server | ASP.NET Core endpoint that receives dispatcher messages from Blazor WASM clients | |
| Arbiter.Dispatcher.Client | Client-side dispatcher for Blazor: JSON/MessagePack (WASM) and ServerDispatcher | |
| Arbiter.Components | Blazor building blocks for list, view, and edit pages |
Communication Providers Packages
| Library | Package | Description |
|---|---|---|
| Arbiter.Communication.Azure | Communication implementation for Azure Communication Services | |
| Arbiter.Communication.Graph | Communication implementation for Microsoft Graph email delivery | |
| 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>andIRequestHandler<TRequest, TResponse> - Notifications/Events: Publish events using
INotificationandINotificationHandler<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.Mappingwith[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
EntityQueryclass 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 IDEntityIdentifiersQuery<TKey, TReadModel>- Get multiple entities by IDsEntityPagedQuery<TReadModel>- Queries both paged and non-paged scenarios with filtering and sorting
Entity Commands:
EntityCreateCommand<TKey, TCreateModel, TReadModel>- Create new entitiesEntityUpdateCommand<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
ProjectTosupport for Entity Framework and other query providers - Record Support: Supports mapping to records,
initproperties, 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.Extensionsfor 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:
IEndpointRouteandMapEndpointRoutesfor modular Minimal API route registrationUseRequestLoggingandUseClaimLoggingmiddleware with logging scopes and activity tags for the user name, id, login provider and authentication method, plus any claims you includeAddDiagnosticRoutesfor theclaims-check,config-debugger,config-reloadandcache-clearroutes, secured by the localhost authorization policy, with configurable redaction of header, cookie and claim valuesProblemDetailsExtensionsfor consistent problem details error responses, with the status code and errors read fromException.Dataand exception details included only in Development unlessProblemDetailsExceptionOptionssays otherwiseForwardedHeadersOptionsSetupto configure the forwarded headers middleware, such as the client address header and trusted proxy networks, from theForwardedHeadersconfiguration 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
- Complete Documentation - Comprehensive guides and API reference
- Quick Start Guide - Get up and running quickly
- Architecture Patterns - Best practices and patterns
- Blazor Dispatcher Overview - Dispatcher architecture, WASM and Server Interactive setup
- Dispatcher Server - Server endpoint configuration, security, and diagnostics
- Dispatcher Client - Client registration, sending commands and queries
- State Management - ModelStateManager, ModelStateLoader, ModelStateEditor
Samples
Explore practical examples in the samples directory:
- Entity Framework Sample - Complete CRUD operations with EF Core
- MongoDB Sample - Document database implementation
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.
- Fork the repository
- Create your feature branch (git checkout -b feature/amazing-feature)
- Commit your changes (git commit -m 'Add amazing feature')
- Push to the branch (git push origin feature/amazing-feature)
- 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:
- Target
net10.0ornet11.0. - Upgrade every Arbiter package to 7.x at the same time.
- Deploy the Blazor WebAssembly client and the dispatcher server together. The MessagePack wire format changed, see MessagePack wire format.
- Drain Service Bus queues that carry MessagePack message bodies before v7 consumers start.
- Update namespaces and replace removed APIs, see Namespace and package moves and Removed APIs.
- 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(or0xc8). - New format for
objectvalues. Values inobjectmembers, such asEntityFilter.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 anobject[]without an error. - .NET formats for
Guid,decimal,DateTimeandDateTimeOffset.Guidanddecimalare written as 16 byte binary,DateTimewithDateTime.ToBinaryandDateTimeOffsetas ticks and offset, the formats of MessagePack'sDotNetOptimizedFormatterFactory. 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
AddMessagePackOptionsnow takes aFunc<MessagePackSerializerOptions, MessagePackSerializerOptions>. MessagePack v4 options are immutable, so return a modified copy. Options passed toconfigurereplace any registered options, so the call can be made before or afterAddDispatcherServiceorAddMessagePackDispatcher:// v6, the action could not change the immutable options services.AddMessagePackOptions(options => { }); // v7 services.AddMessagePackOptions(options => options with { MaxBufferedMessageSize = 128 * 1024 * 1024 });CustomFormatterResolverandTypePreservingFormatterare removed.MessagePackDefaultsexposesDefaultFormatterFactory,DefaultFormatterResolverandDefaultSerializerOptions, andCreateFormatterFactoryto 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(...)byoptions with { Resolver = ... }, andWithCompressionby theMessagePack.LZ4package.MessagePack.Annotationsis 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.Extensionsstill exists forQueryExtensions,ExceptionExtensions,PrincipalReaderExtensionsandToIdentifierList. With only thatusing, the moved extension methods no longer resolve: addusing Arbiter.Services.Extensions;.- Arbiter.CommandQuery.Endpoints and Arbiter.CommandQuery.Mvc reference Arbiter.Server, so no new package reference is needed, only
using Arbiter.Server;. AddEndpointRoutesstays inArbiter.CommandQuery.Endpoints, in theEndpointServiceExtensionsclass.- Arbiter.CommandQuery no longer references the
Microsoft.Extensions.DependencyInjection,Microsoft.Extensions.ConfigurationandMicrosoft.Extensions.Httppackages. Projects that used them through Arbiter, for exampleBuildServiceProvider,ConfigurationBuilderorAddHttpClientin 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:
EntityCommandEndpointBaseno longer mapsPATCH {id}, andEntityCommandControllerBaseno longer has thePatchaction orPatchCommand.PATCHrequests to those routes now return 405 Method Not Allowed.AddEntityCommandsno longer registers a patch handler.- Arbiter no longer references
SystemTextJsonPatch. Code that usesJsonPatchDocumentmust reference the package directly.
Signature changes
RequestLoggingOptions.IncludeRequestBodychanged fromboolto theRequestBodyLoggingenum (Never,Always,OnError). ReplacetruewithRequestBodyLogging.Always, including in configuration files.ITemplateService.ApplyTemplate<TModel>(source, model)is nowApplyTemplate<TModel>(templateName, source, model). Parsed templates are cached bytemplateNamefor the lifetime of the service; passnullto parse without caching.- The
BaseAddressResolverconstructors take anIOptions<EnvironmentOptions>, registered byAddEnvironmentOptions,AddCommandQueryorAddEndpointRoutes. - The communication services take an
IOptionsMonitor<EmailConfiguration>orIOptionsMonitor<SmsConfiguration>in place ofIOptions<T>, followed by an optionaloptionsNamefor keyed services, so a configuration reload applies to the next message. This coversEmailTemplateService,SmsTemplateService,SmtpEmailDeliveryService,SendGridEmailDeliveryService,TwilioSmsDeliveryService,AzureEmailDeliveryService,AzureSmsDeliveryServiceandGraphEmailDeliverService. In tests, replaceOptions.Create(configuration)with anIOptionsMonitor<T>. EmailTemplateService.Optionsis the currentEmailConfiguration, not anIOptions<EmailConfiguration>. ReplaceOptions.Value.FromNamewithOptions.FromName.- The
AddKeyedEmailDeliveryandAddKeyedSmsDeliverfactories receive the options monitor and the options name: replace(serviceProvider, options) => ...with(serviceProvider, options, optionsName) => ...and readoptions.Get(optionsName). AddMessagePackOptions, see MessagePack options and custom serialization code.
Behavior changes
Diagnostics authorization. The default
DiagnosticsEndpointOptions.AuthorizationPolicyis nowArbiter.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
AddEndpointRoutesandAddDiagnosticRoutesare called.Environment name.
EnvironmentOptions.EnvironmentNamedefaults toIHostEnvironment.EnvironmentNamewhen a host environment is registered. A value set in configuration or code still wins.User name claim.
GetUserNamereadspreferred_username,upn,ClaimTypes.Upn,unique_name,ClaimTypes.Name, thensub. v6 readpreferred_username,ClaimTypes.Name, thensub. Values such asCreatedByandUpdatedBycan change for identity providers that send aupnorunique_nameclaim.Entity Framework optimistic concurrency.
EntityUpdateCommandHandlernow checks the update model'sRowVersionagainst the stored row, when the model implementsITrackConcurrencyand the entity has along RowVersionproperty configured as a concurrency token. If the row was changed or deleted after the caller loaded it, the update fails with aDomainExceptionwith status code 409 (Conflict), and the endpoints and the dispatcher return 409. v6 ignored the caller'sRowVersionand overwrote the newer change. Send theRowVersionof the latest read model, such as the one returned by the previous save; aRowVersionof0skips the check. The Entity Framework command handlers throw thisDomainExceptionin place ofDbUpdateConcurrencyException, which becomes its inner exception, so code that catchesDbUpdateConcurrencyExceptionmust catchDomainExceptioninstead.Problem details. The
exceptionstack trace is included only in the Development environment by default. Change it withProblemDetailsExceptionOptions.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 asdetail. v6 returned the message of its innermost exception. The title for status code 409 isConflict.FilterOperators.NotIn. Fixed. In v6 a
NotInfilter threw aParseException.Types in MessagePack
objectmembers. A value in anobject, 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 withMessagePackSerializationException: 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-Typeheader names a type that is not a concreteIRequest, 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 enhancedEntityQuerythat now supports both paged and non-paged results - Removed
EntityUpsertCommand: Upsert functionality has been unified intoEntityUpdateCommandwith built-in upsert logic - Removed
EntityContinuationQueryandEntityContinuationResult: Functionality now integrated intoEntityQuery - Command/Query Reorganization:
- Moved query classes (
EntityIdentifierQuery,EntityIdentifiersQuery,EntityPagedQuery) toCommandsnamespace for better organization - Renamed base classes for consistency:
EntityIdentifierCommand→EntityIdentifierBaseEntityIdentifiersCommand→EntityIdentifiersBaseEntityModelCommand→EntityModelBase
- Renamed filter, logic, and sort values for more consistent query building
EntityFilterOperators→FilterOperatorsEntityFilterLogic→FilterLogicEntitySortDirections→SortDirections
- Moved query classes (
Architecture Improvements
Simplified Query System:
- Consolidated multiple query types into a single, more powerful
EntityQueryclass - Removed redundant query handlers and behaviors
- Enhanced filter and sort capabilities with better type safety
- Consolidated multiple query types into a single, more powerful
Enhanced Filtering:
- Moved filter logic to dedicated
Queries.FilterLogicandQueries.FilterOperatorsenums - Improved
EntityFilterConverterwith better validation and error handling - Enhanced
LinqExpressionBuilderwith more robust query building capabilities
- Moved filter logic to dedicated
Caching Simplification:
- Removed
DistributedCacheQueryBehaviorandMemoryCacheQueryBehavior - Consolidated caching logic into
HybridCacheQueryBehaviorfor better performance - Removed
IDistributedCacheSerializerinterface in favor of built-in serialization
- Removed
Behavior Consolidation
Tenant Behaviors:
- Removed
TenantFilterBehaviorBaseandTenantSelectQueryBehavior - Enhanced
TenantPagedQueryBehaviorto handle all tenant-related query filtering
- Removed
Soft Delete Behaviors:
- Removed
DeletedFilterBehaviorBaseandDeletedSelectQueryBehavior - Enhanced
DeletedPagedQueryBehaviorto handle all soft delete scenarios
- Removed
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 | Versions 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. |
-
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.