Xpandables.Net
11.0.2
dotnet add package Xpandables.Net --version 11.0.2
NuGet\Install-Package Xpandables.Net -Version 11.0.2
<PackageReference Include="Xpandables.Net" Version="11.0.2" />
<PackageVersion Include="Xpandables.Net" Version="11.0.2" />
<PackageReference Include="Xpandables.Net" />
paket add Xpandables.Net --version 11.0.2
#r "nuget: Xpandables.Net, 11.0.2"
#:package Xpandables.Net@11.0.2
#addin nuget:?package=Xpandables.Net&version=11.0.2
#tool nuget:?package=Xpandables.Net&version=11.0.2
System.Net
Shared foundation package providing Result types, optionals, collections, JSON contexts, caching, correlation state, and general utilities
Features • Getting Started • Result Pattern • Optionals • Collections • Utilities • AOT Compatibility
📋 Overview
Xpandables.Net is the shared foundation package for the Xpandables ecosystem. It contains the System.Results,
System.Collections, System.Optionals, System.States and System.Composition types, and the shared JSON, cache,
correlation, cryptography and HTTP utilities used by the other packages. It targets .NET 11, has no reflection-based
code path, and is Native AOT and trimming safe.
🎯 Key Features
| Feature | Description |
|---|---|
| ✅ Result Pattern | Result / Result<TValue> carrying an HTTP status code, title, detail, location, errors, headers, extensions and exception; factory methods, fluent builder, Match/Map/Bind/LINQ, merge strategies |
| ❔ Optionals | Optional<T> value-or-nothing struct with Map/Bind/Empty, async variants, LINQ, comparison and JSON support |
| 🔗 Element Collections | ElementCollection — thread-safe, insertion-ordered, case-insensitive key → values collection of ElementEntry |
| 🌐 HTTP Status Extensions | IsSuccess, IsFailure, Title, Detail, EnsureSuccess(), GetException() and 30+ predicates on HttpStatusCode |
| ⚠️ Exception Utilities | Exception → Result, GetHttpStatusCode(), GetElementEntries() (problem-details aware), GetFullExceptionMessage() |
| 🧩 Service Composition | IAddService modules and the [CacheType] name map, registered by source-generated code |
| 🎁 Decorators | XTryDecorate wraps existing service registrations, in registration order |
| 🧭 Ambient Context | CorrelationContext with an AsyncLocal accessor, and RequestScopeAccessor for the current request scope |
| 🔄 State Pattern | State<TContext> / StateContext<TState> with lock-free, compare-and-swap transitions and events |
| 🧰 Utilities | MIME types, weak-reference cache, AES-256-GCM text encryption, PBKDF2 password hashing, random text, culture-aware formatting, Disposable / DisposableAsync |
| 🚀 AOT Ready | Source-generated JSON contexts and source-generated registrations, no reflection fallback |
🚀 Getting Started
Installation
dotnet add package Xpandables.Net
The package brings Xpandables.Generators with it (its analyzer flows to your project): nothing else needs to be
installed for the generated registrations and Optional<T> converters described below.
🔧 Dependency Injection
The package is usable without dependency injection. Register the optional infrastructure services only when the
application needs them. All registration methods live in Microsoft.Extensions.DependencyInjection. A method that
takes your implementation (AddXJsonSerializerContext<TContext>(), AddXHttpStatusCodeExtension<TExtension>(),
AddXCacheTypeResolver<TResolver>() / (Type)) replaces any earlier registration of the service, whatever the order;
the default ones (AddXJsonSerializerContext(), AddXHttpStatusCodeExtension()) and the generated
AddX{Assembly}CacheTypes() of each project register only when the service is not registered yet. The default
IJsonSerializerContext reads the registered JsonSerializerOptions, and says so when there is none.
| Method | Registers |
|---|---|
AddXJsonSerializerContext() |
IJsonSerializerContext → DefaultJsonSerializerContext (singleton) |
AddXJsonSerializerContext<TContext>() |
IJsonSerializerContext → your implementation (singleton) |
AddXHttpStatusCodeExtension() |
IHttpStatusCodeExtension → HttpStatusCodeExtension (singleton) |
AddXHttpStatusCodeExtension<TExtension>() |
IHttpStatusCodeExtension → your implementation (singleton) |
AddXCacheTypeResolver<TResolver>() / AddXCacheTypeResolver(Type) |
ICacheTypeResolver → your implementation (singleton) |
AddXServicesGenerated(configuration) / AddXServicesGenerated() |
every IAddService module (source-generated) |
AddXCacheTypes(CacheTypeRegistration) |
Adds one assembly's cache types; ICacheTypeResolver → CacheTypeResolver over the merged maps of every assembly. Called by the generated AddX{Assembly}CacheTypes() of each project |
using Microsoft.Extensions.DependencyInjection;
// DefaultJsonSerializerContext takes the JsonSerializerOptions registered in the container and requires a
// source-generated resolver on them (see "AOT Compatibility").
services.AddSingleton(new JsonSerializerOptions
{
TypeInfoResolverChain = { AppJsonContext.Default, OptionalJsonContext.Default },
});
services.AddXJsonSerializerContext();
services.AddXHttpStatusCodeExtension();
// Or a custom implementation
services.AddXJsonSerializerContext<MyJsonContext>();
IJsonSerializerContext exposes the SerializerOptions and ResolveJsonTypeInfo(Type); the extension
ResolveJsonTypeInfo<T>() returns a typed JsonTypeInfo<T>. DefaultJsonSerializerContext.ResolveJsonTypeInfo
throws InvalidOperationException for a type its resolvers do not know.
Excluding a type from generated registration
[ExcludeFromRegistration] (namespace System) leaves a type out of every registration the Xpandables generators
write — service modules, endpoint routes, repositories, event consumers, handlers and validators — so you register it
yourself (with another lifetime, a key, a factory) or not at all. The generators match the attribute by its name, in any
namespace: a project without Xpandables.Net declares its own ExcludeFromRegistrationAttribute.
[ExcludeFromRegistration]
public sealed class LegacyOrderHandler : IRequestHandler<PlaceOrder> { /* registered by hand */ }
Service modules (source-generated)
Implement IAddService (or derive from AddService, whose configuration overload calls the plain one by default)
to group registrations:
using System.Composition;
public sealed class OrderingServices : AddService
{
public override void AddServices(IServiceCollection services) =>
services.AddScoped<IOrderRepository, OrderRepository>();
}
// Program.cs
builder.Services.AddXServicesGenerated(builder.Configuration); // calls AddServices(services, configuration)
// or builder.Services.AddXServicesGenerated(); // calls AddServices(services)
Every concrete IAddService in the application, and in referenced assemblies that are or reference an
Xpandables.* assembly, is discovered at compile time. The generated code calls new T() on each module (in ordinal
order of their full names), so no reflection or assembly scanning is involved.
- The generated
AddXServicesGeneratedandAddX{Assembly}CacheTypesalways exist in an application (an executable project), so the call compiles before the first module or[CacheType]is declared. A library gets them only when it declares something to register. - The generated extension classes are
internal: call them from the application project itself. - Abstract, static, generic, file-local, inaccessible and
ref structtypes are skipped. A module the generated code cannot construct (no accessible parameterless constructor,[Obsolete]on it or a containing type, required members without[SetsRequiredMembers], or declared inside a generic type) is reported as warningXSR001.
Decorators
XTryDecorate replaces every non-keyed registration of a service with one that wraps it. Decorators apply in
registration order (the first registered wraps the original service, the next wraps the first, and so on). The
decorated registration keeps the lifetime of the registration it wraps. When the service is not registered, nothing
happens. An open generic service type (typeof(IHandler<>)) decorates every closed registration of it.
services.AddScoped<IOrderService, OrderService>();
services.XTryDecorate<IOrderService, LoggingOrderService>(); // type: constructor-injected, wrapped service included
services.XTryDecorate<IOrderService>((inner, provider) => new CachingOrderService(inner, provider.GetRequiredService<IMemoryCache>()));
services.XTryDecorate<IOrderService>(inner => new TimingOrderService(inner));
services.XTryDecorate(typeof(IOrderService), typeof(AuditOrderService)); // non-generic overloads also take a Func<object, …>
A decorator type is built by an ObjectFactory made once with ActivatorUtilities.CreateFactory (annotated for the
trimmer), the way Microsoft's container builds every registered type.
Each registration is replaced by a factory registration, and the original is registered again under a key of its own (an object no other code holds). The container builds the wrapped service from it, with its lifetime, and tracks and disposes it like any other service (an instance you registered stays yours and is not disposed). The container must support keyed services (Microsoft's does); a
GetKeyedServices(type, KeyedService.AnyKey)call sees these keyed originals, and a laterReplaceorRemoveAllof the service type leaves them registered.A decorator type is checked when decorating: it must implement the service type (
ArgumentException) and have a constructor taking it (InvalidOperationException). Its constructor is found once, not on each resolution.Decorating a service that is not registered does nothing; decorating a closed generic service (
IHandler<Order>) served only by an open generic registration throwsInvalidOperationException.Keyed registrations of the service type are not decorated by
XTryDecorate;XTryDecorateKeyeddecorates the registrations of one key, the same way:services.XTryDecorateKeyed<IOrderService, LoggingOrderService>("reporting"); services.XTryDecorateKeyed<IOrderService>("reporting", (inner, provider) => new TimingOrderService(inner));The original is kept under a
DecoratedServiceKey(its implementation type and its key).TryAddEnumerableno longer recognises a decorated implementation, so registering it again would add it a second time, undecorated:XTryAddEnumerable(descriptor)reads the key and adds nothing. The Xpandables libraries register their enumerable services (behaviors, validators, consumers, composers, interceptors) with it.With an open generic service type, the decorator must be a delegate or a closed type that fits every closed registration. An open generic decorator type (
typeof(LoggingHandler<>)) throwsArgumentException, and an open generic registration (services.AddScoped(typeof(IHandler<>), typeof(Handler<>))) throwsInvalidOperationExceptionwhen decorating: a factory registration cannot serve an open generic service type.
Lazy resolution
LazyResolved<T> is a Lazy<T> built from an IServiceProvider, for registering Lazy<> as an open generic
service. It resolves T with GetRequiredService<T>() on the first read of Value, once and thread-safely: resolving
Lazy<T> creates nothing (IsValueCreated is false), and a missing registration of T throws
InvalidOperationException from Value. T comes from the provider that resolved the Lazy<T>: read Value while
that scope is alive, or it throws ObjectDisposedException. Like any Lazy<T>, a failed first read is cached and
every later read throws the same exception.
services.AddTransient(typeof(Lazy<>), typeof(LazyResolved<>));
✅ Result Pattern
A Result represents the outcome of an operation with an HTTP status code. Errors are captured as values rather than
thrown. IsSuccess is true for 2xx, IsInformational for 1xx, and IsFailure for 4xx and 5xx; a redirect (3xx) is
neither a success nor a failure.
| Member | Description |
|---|---|
StatusCode |
The HttpStatusCode (default OK) |
Title / Detail |
Short summary and occurrence-specific explanation |
Location |
A Uri relevant to the outcome |
Errors / Headers / Extensions |
ElementCollections, created when first used |
HasErrors / HasHeaders / HasExtensions |
Whether each holds entries, without creating it (never serialized) |
Exception |
The exception attached (never serialized) |
Value (Result<TValue>) |
The typed value; default when unset |
GetObjectValue() / TryGetValue<T>(out T) |
Untyped access, and type-checked access without casting |
Creating Results
using System.Net;
using System.Results;
// Success
Result ok = Result.Success(); // 200
Result<User> user = Result.Success(new User { Id = 1 }); // 200 with a value
Result<User> accepted = Result.Success(new User { Id = 3 }, HttpStatusCode.Accepted);
Result created = Result.Created(); // 201
Result<User> createdUser = Result.Created(new User { Id = 2 });
Result noContent = Result.NoContent(); // 204
Result queued = Result.Accepted(); // 202
// Failure
Result failure = Result.Failure(); // 400
Result<User> missing = Result.Failure<User>(HttpStatusCode.NotFound);
Result notFound = Result.NotFound("id", "User 42 does not exist"); // 404 + error
Result<User> conflict = Result.Conflict<User>("email", "Already taken"); // 409 + error
Result crash = Result.InternalServerError(exception); // 500 + exception
Result unauthorized = Result.Unauthorized(); // 401
Result forbidden = Result.Forbidden(); // 403
Result unprocessable = Result.UnprocessableEntity(); // 422
Result unavailable = Result.ServiceUnavailable(); // 503
Each named helper also has a <TValue> overload.
Fluent Builder
With* methods mutate the instance and return it for chaining. The typed overloads of WithError, WithErrors and
WithException return Result<TValue>.
Result result = Result
.Failure(HttpStatusCode.BadRequest)
.WithTitle("Validation failed")
.WithDetail("See errors")
.WithError("email", "Email is required")
.WithError(new ElementEntry("age", "Must be at least 18"))
.WithHeader("Retry-After", "30")
.WithExtension("traceId", traceId)
.WithLocation(new Uri("/orders/42", UriKind.Relative))
.WithException(new ValidationException("Invalid input"));
WithStatusCode, WithValue, WithErrors, WithHeaders and WithExtensions complete the set. A second
WithException combines both exceptions into an AggregateException.
Value Access
Result<Product> result = FetchProduct(id);
// A success may carry no value (NoContent, Accepted, Success(null)): Value is read as maybe null
if (result.IsSuccess && result.Value is { } found)
{
Console.WriteLine(found.Name);
}
// Type-checked access on any Result, without casting
if (result.TryGetValue(out Product? product)) { /* ... */ }
// Re-type a result, keeping status, title, detail, location, errors, headers, extensions and exception
Result<string> asString = result.ToResult<string>();
ToResult<TValue>() (and Map, Bind and Try on a failure, which use it) copies the Errors, Headers and
Extensions of the source result: a later With* call on one is not seen by the other. Its value is the
value argument when it is a TValue, else the source value when it is one, else default.
Monadic Operations
Match, Switch, Map, Bind, Select and SelectMany compose Result<TValue>. On failure, Map/Bind carry
the failing result over to the new value type. fail receives every result that is not a success (2xx): a failure,
and also a redirect (3xx) or an informational result; Map/Bind carry it over unchanged. On success, Map keeps
everything the result carries (status, title, detail, location, errors, headers, extensions and exception) with the
mapped value. Their delegates receive a
TValue?: a success may carry no value (NoContent, Accepted), and then receives the default one.
Result<User> result = FetchUser(id);
string message = result.Match(
ok: user => $"Found: {user?.Name}",
fail: r => $"Error: {r.StatusCode}");
Result<string?> name = result.Map(user => user?.Name);
Result<Order> order = result.Bind(user => user is null ? Result.NotFound<Order>("user", "No user.") : FetchOrder(user.Id));
result.Switch(
ok: user => Console.WriteLine(user?.Name),
fail: r => Console.WriteLine(r.StatusCode));
// LINQ query syntax
Result<OrderSummary> summary =
from user in FetchUser(id)
from o in FetchOrder(user!.Id) // FetchUser never succeeds without a user
select new OrderSummary(user.Name, o!.Total);
Implicit Conversion
A value converts implicitly to a Result<TValue>: a value is a success carrying it (Result.Success(value)), null
is a 404 failure without a value (Result.NotFound<TValue>()). An explicit Result.Success<TValue>(null) is a success
without a value, as is Result.NoContent<TValue>(), which carries none.
Result<User> result = new User { Id = 1, Name = "Alice" }; // 200
Result<User> missing = repository.Find(42); // 404 when Find returns null
Try / TryAsync
Try runs a delegate and TryAsync awaits a task; a thrown ResultException returns its own result, any other
exception is converted with ToResult() (see below).
Result<int> parsed = ((Func<int>)(() => int.Parse("123"))).Try();
Result done = ((Action)(() => Save())).Try();
Result withArg = ((Action<Order>)Save).Try(order);
Result<User> user = await FetchUserAsync(id).TryAsync();
Result saved = await SaveAsync(order).TryAsync();
Exception to Result
Result result = exception.ToResult(); // status from GetHttpStatusCode()
Result custom = exception.ToResult(HttpStatusCode.BadGateway, reason: "Upstream failed");
- The title is the status title, or the
reasonyou pass: the exception message never becomes the title by itself. The detail is the status detail. The exception is attached to the result, and the errors come fromexception.GetElementEntries(), so a problem-detailserrorsobject carried by the message (a downstream API's failure) becomes the result's errors. - A
ValidationExceptionbecomes a 400 titledOne or more validation errors occurred.with its validation results as errors (aMultipleValidationExceptioncontributes all of them). - A
ResultExceptionbecomes a failure with its result's status code, that code's title and detail, and its result's errors, extensions and headers. - For these two, the
statusCodeandreasonarguments are ignored and the exception is not attached.
Validation Results
using System.ComponentModel.DataAnnotations;
using System.Results;
var results = new List<ValidationResult>
{
new("Email is required", ["email"]),
new("Age must be 18+", ["age"]),
};
Result validation = results.ToResult();
// 400, title "One or more validation errors occurred.", errors { email → …, age → … }
Result fromException = new ValidationException("Email is required").ToResult();
ToResult() on an empty sequence throws ArgumentOutOfRangeException. An error that names no member (an
IValidatableObject rule across properties) is kept under ValidationResultExtensions.ObjectLevelKey, $, as
System.Text.Json and ASP.NET Core name the root object. An error with several member names is recorded under each of
them. validationResult.ToElementCollection() and validationResults.ToElementCollection() give the same entries
without building a result.
Problem-details messages
Result r = "Response: 409 {\"title\":\"Conflict\",\"errors\":{\"sku\":[\"Taken\"]}}".ToResult();
ElementCollection errors = message.ToErrors();
string.ToResult() reads the first balanced {…} or […] segment of the message; when it is a JSON object, it reads
it as problem details: status (or else the
status code that follows the message's first colon, as in ...: 409 {...}, or else 400), title and detail
(defaulting to the status code's title and detail), errors, instance (as Location) and any other property
except type (as an extension). A message without such a payload becomes a 400 whose title is the message. ToErrors() returns only the errors section, or
an empty collection.
ToResult(this ReadOnlySpan<byte> utf8Content) reads UTF-8 bytes: a problem-details object (after an optional BOM and white space) is parsed from the bytes without decoding them; any other content is decoded and read as ToResult(string) reads it (a status prefix or an embedded payload included)
(System.Rests uses it for a failure body).
Merge Results
Merge returns a new Result; neither operand is modified. The status is the first result's, unless the second is a
failure and the first is not, or both fail and the second's status is greater: the failure wins (a failure is a 4xx or
5xx status), then the higher failure. The title and detail come with the status kept (when both results have it, the
second's non-empty ones first); the location and value are the first result's. Errors, headers and extensions are
combined according to a MergeStrategy, and exceptions are combined.
Result first = Result.Failure().WithError("code", "error1");
Result second = Result.Failure().WithError("code", "error2");
var merged = first.Merge(second); // Concat (default): ["error1", "error2"]
var replaced = first.Merge(second, MergeStrategy.Replace); // ["error2"]
var kept = first.Merge(second, MergeStrategy.KeepExisting); // ["error1"]
var strict = first.Merge(second, MergeStrategy.Throw); // InvalidOperationException on the duplicate key
Equality
Results of the same type compare by value: status code, title, detail, location, errors, headers, extensions and
value (the exception is not compared). A Result never equals a Result<TValue>.
bool equal = Result.Success(42) == Result.Success(42); // true
ResultException
ResultException carries a failure Result through code that throws: result.ToResultException() or
new ResultException(result). Its constructors require a failure status (EnsureFailure() throws
InvalidOperationException otherwise). Try/TryAsync and ToResult() unwrap it.
❔ Optionals
Optional<T> (System.Optionals) is a readonly record struct that holds a value or nothing. A null value is
always empty, so a non-empty optional never holds null.
using System.Optionals;
Optional<User> some = Optional.Some(user);
Optional<User> none = Optional.Empty<User>();
Optional<User> fromValue = user; // implicit: null becomes empty
Optional<string> fromNullable = maybeName.ToOptional();
User u = some.Value; // InvalidOperationException when empty
User fallback = none.GetValueOrDefault(User.Guest);
User lazy = none.GetValueOrDefault(() => LoadGuest());
bool present = some.IsNotEmpty; // IsEmpty is the opposite
if (some.TryGetValue(out User? found)) { /* ... */ }
User cast = (User)some; // explicit: throws when empty
| Operation | Description |
|---|---|
Map(Func<T, T>) / Map(Func<T, Optional<T>>) / Map(Action<T>) / Map(Action) |
Run on a value; empty stays empty |
Bind<TU>(Func<T, TU>) / Bind<TU>(Func<T, Optional<TU>>) |
Project to another type |
Empty(Func<T>) / Empty(Func<Optional<T>>) / Empty(Action) |
Run only when empty (fallback) |
ToOptional<TU>() |
The value as TU when it is one, otherwise empty |
MapAsync, BindAsync, EmptyAsync |
Async forms returning ValueTask<Optional<T>> (no allocation when the delegate's task has completed, the three-argument SelectManyAsync aside), on Optional<T>, ValueTask<Optional<T>> and Task<Optional<T>> |
Where, Select, SelectMany, SelectAsync, SelectManyAsync |
LINQ support |
Optional<string> email =
from customer in FindCustomer(id)
where customer.IsActive
select customer.Email;
Optional<Order> first = orders.FirstOrEmpty(o => o.IsOpen);
IEnumerable<Order> present = optionals.WhereSome();
Optional<Order> firstAsync = await asyncOrders.FirstOrEmptyAsync();
Optional<T> enumerates zero or one item, compares and sorts (empty sorts first; <, <=, >, >= are
defined), implements IFormattable, and its ToString() is the value's text or an empty string.
JSON
An empty optional is written as null and a non-empty one as its value; null reads back as empty. Add
OptionalJsonConverterFactory to the options (or to your context's [JsonSourceGenerationOptions(Converters = …)]):
[JsonSourceGenerationOptions(Converters = [typeof(OptionalJsonConverterFactory)])]
[JsonSerializable(typeof(MoneyOrder))]
internal sealed partial class AppJsonContext : JsonSerializerContext;
public sealed record MoneyOrder(Optional<Money> Total, Optional<string> Label);
The wrapped value's metadata comes from your options' resolver, falling back to OptionalJsonContext for the
built-in types (string, int, long, short, float, double, decimal, ushort, byte, bool, DateTime,
DateTimeOffset, Guid); when neither knows T, reading or writing throws JsonException. The converter for every
other Optional<T> is generated (see
AOT Compatibility); a T with no converter makes the factory throw NotSupportedException
naming the OptionalJsonConverters.Register<T>() call to make.
🔗 Element Collections
ElementCollection (System.Collections) maps keys to one or more string values. Result uses it for errors,
headers and extensions.
ElementEntry
ElementEntry is an immutable sealed record of a Key and StringValues Values. Its constructor requires at
least one value.
using System.Collections;
var single = new ElementEntry("email", "Email is required");
var multi = new ElementEntry("roles", new StringValues(["admin", "user"]));
ElementCollection
- Thread-safe: writes and key lookups take an internal lock; the count and the enumeration read an immutable snapshot, published under the lock and replaced by the next write, so enumerating while other threads write never throws.
- Insertion-ordered, case-insensitive keys (
OrdinalIgnoreCase, as HTTP header names are). Addmerges into an existing key (its values are appended unless they are identical); a null or empty key throws.- Equality is content-based and ignores entry order. The collection is mutable, so do not use it as a dictionary key.
- No static empty instance: use
[].
ElementCollection empty = [];
ElementCollection errors = ElementCollection.With("email", "Required");
ElementCollection others = [new ElementEntry("name", "Required"), new ElementEntry("age", "Must be 18+")];
ElementCollection fromDict = ElementCollection.FromDictionary(dictionary);
errors.Add("age", "Must be 18+");
errors.AddRange([new ElementEntry("email", "Invalid format")]);
errors.Merge(others);
errors.Remove("name");
// Lookup
ElementEntry? byIndexer = errors["email"]; // null when absent
if (errors.TryGetEntry("email", out ElementEntry? entry))
{
Console.WriteLine(entry.Values); // "Required,Invalid format"
}
string? first = errors.TryGetStringEntry("email");
StringValues values = errors.GetStringValues("email"); // KeyNotFoundException when absent
ElementCollection headers = ElementCollection.With("Retry-After", "30");
int retryAfter = headers.GetValue("retry-after", (string v) => int.Parse(v, CultureInfo.InvariantCulture)); // TryGetValue: default when absent
// Operators return new collections and leave the operands unchanged
ElementCollection plus = errors + new ElementEntry("x", "y");
ElementCollection minus = errors - "email";
ElementCollection diff = errors - others;
// Conversion
ReadOnlyDictionary<string, StringValues> readOnly = errors.ToReadOnlyDictionary();
Dictionary<string, StringValues> mutable = errors.ToDictionary();
ElementCollection copy = errors.Copy();
string text = errors.ToString(); // "key=v1,v2" lines
GetValue and TryGetValue take a Converter<string, T> (the values joined with commas) or a
Converter<StringValues, T>; type the lambda parameter to pick one. GetValue, GetEntry, GetStringEntry and
GetStringValues throw KeyNotFoundException for an absent key; a null or empty key throws ArgumentException.
Related extensions: IEnumerable<ElementEntry>.ToJsonString() (compact JSON, for any sequence of entries),
ToDictionaryObject() and ToDictionaryString() (values joined by spaces); HttpHeaders.ToElementCollection() (header
values as received; a header without a value adds no entry); string.ToElementCollection()
(deserializes the JSON form); IEnumerable<T>.StringJoin(separator).
Serialization
ElementCollection and ElementEntry carry their converters ([JsonConverter]), so every context and options
instance uses them. A collection is a JSON array (null reads as an empty collection); an entry's values are always
written as an array and read either as an array or as a single string:
[
{ "key": "email", "values": ["Required", "Invalid format"] },
{ "key": "age", "values": ["Must be 18+"] }
]
🌐 HTTP Status Code Extensions
using System.Net;
HttpStatusCode code = HttpStatusCode.NotFound;
bool isSuccess = code.IsSuccess; // false (2xx)
bool isFailure = code.IsFailure; // true (4xx or 5xx)
bool isClientError = code.IsClientError; // true (4xx); also IsServerError, IsRedirect, IsInformational, IsValidationProblem
bool isNotFound = code.IsNotFound; // one predicate per common code: IsOk, IsCreated, IsConflict, IsTooManyRequests, …
string title = code.Title; // "Not Found" ("Success" for 200, "Unknown" for an unlisted code)
string detail = code.Detail; // "The request could not be processed." (a 401 and a 5xx have their own)
code.EnsureFailure(); // InvalidOperationException unless 4xx or 5xx
HttpStatusCode failure = code.Failure(); // returns the code, throws unless 4xx or 5xx
// code.EnsureSuccess() / code.Success() // throw InvalidOperationException for a failure code
Exception ex = code.GetException("User not found"); // ResultException carrying 404
IHttpStatusCodeExtension (GetTitle, GetDetail, GetException) exposes the same mapping as a service.
HttpStatusCodeExtension is the default; derive from it (its members are virtual) to localize titles or details and
register it with AddXHttpStatusCodeExtension<T>().
⚠️ Exception Extensions
HttpStatusCode code = new ValidationException("Name is required.").GetHttpStatusCode(); // 400
// Errors from validation exceptions and from problem-details JSON in messages, across inner and aggregate exceptions
ElementCollection errors = new HttpRequestException("Response: 400 {\"errors\":{\"email\":[\"Required\"]}}")
.GetElementEntries();
// Every message of the chain, one per line
string fullMessage = new InvalidOperationException("Outer", new ArgumentException("Inner")).GetFullExceptionMessage();
Status code ⇄ exception mapping
| Exception (first match wins) | Status |
|---|---|
ResultException |
its result's status |
ValidationException (and MultipleValidationException) |
400 |
AuthenticationException |
401 |
UnauthorizedAccessException, SecurityException |
403 |
DBConcurrencyException |
409 |
TimeoutException |
504 |
HttpRequestException whose inner exception is a TimeoutException, or carrying 408 or 504 |
504 |
any other HttpRequestException (an upstream call failed) |
502 |
OperationCanceledException caused by a TimeoutException |
504 |
any other OperationCanceledException |
499 (client closed request); a host answers 500 when the request was not aborted |
anything else (ArgumentException, FormatException, KeyNotFoundException, FileNotFoundException, NotSupportedException, InvalidDataException, NotImplementedException...) |
500 |
An exception of the application maps through an IExceptionStatusMapper registered in the container
(services.AddSingleton<IExceptionStatusMapper, MyMapper>()): Xpandables.AspNetCore.Net consults it first.
HttpStatusCode.GetException(message) is the inverse: 401 AuthenticationException, 403 UnauthorizedAccessException,
500 InvalidOperationException, 504 TimeoutException, a ResultException carrying the code for every other 4xx and
5xx code, so code.GetException(m).GetHttpStatusCode() == code for every 4xx and 5xx code, and an
HttpRequestException carrying the code for any other code.
Validation exceptions
ValidationException ex = validationResults.ToValidationException();
// one result → ValidationException; several → MultipleValidationException (ValidationResults holds them all)
// an empty sequence → InvalidOperationException
ToResult() of validation results or of a ValidationException keys the errors by JSON name: a member path goes
through the JsonNamingPolicy passed (null: camelCase), a JSON path ($.name) is kept as written after $..
🧭 Type resolution by name
ICacheTypeResolver maps a persisted name back to a CLR type: Resolve(name) throws InvalidOperationException
for an unknown name, TryResolve(name) returns null. Mark the types with [CacheType] (or implement
System.Events.IEvent, named by [EventName]) and register the generated map of each project that declares some:
[CacheType("Ordering.OrderPlaced.v1")]
public sealed record OrderPlaced(Guid OrderId);
builder.Services.AddXShopApiCacheTypes(); // this project's cache types, internal ones included
builder.Services.AddXShopOrdersCacheTypes(); // and each referenced project's: the resolver merges them
- The name is a wire contract: once values are stored under it, keep it even if the type is renamed or moved. Without a name, the type's simple name is used.
- Each project registers its own types,
internalones included, with its generatedAddX{Assembly}CacheTypes()(class{Assembly}CacheTypeRegistrations): a domain can keep its events internal. Calling it twice adds nothing. - Two types sharing a name are a compile-time error (
XCT001); an empty or whitespace name isXCT002. The check spans projects: each project records its names as[assembly: AssemblyMetadata]entries, and a project that references another reports a clash with its own names; an application reports clashes between any two projects it references. - An
IEventtype is registered under its[EventName](or its type name);[CacheType]names every other type. CacheTypeResolvercopies its map into aFrozenDictionarywith ordinal comparison; it holds no static state. Register a hand-built one withservices.AddSingleton<ICacheTypeResolver>(new CacheTypeResolver(map)).
🔁 Correlation and request scope
CorrelationContext carries a CorrelationId and a CausationId. AsyncLocalCorrelationContextAccessor
(an ICorrelationContextAccessor) flows it with the logical execution: a child async flow sees the parent's context,
and changes in a child do not reach the parent. Current is the default context outside any scope. The storage is
static: every instance of the accessor sees the same ambient context.
using (accessor.BeginScope(new CorrelationContext { CorrelationId = id, CausationId = causeId }))
{
// accessor.Current is the context here
}
// the previous context (or none) is restored
BeginScope requires the accessor to be an AsyncLocalCorrelationContextAccessor and throws
InvalidOperationException otherwise.
RequestScopeAccessor flows the current request-scoped IServiceProvider the same way, so singletons resolve scoped
services from the caller's scope instead of an isolated child scope. The pipeline entry point sets it; when
Current is null (a background service), create a scope with IServiceScopeFactory.
using (RequestScopeAccessor.BeginScope(scope.ServiceProvider))
{
IServiceProvider? current = RequestScopeAccessor.Current;
}
🔄 State Pattern
System.States provides IState, IStateContext, the State<TStateContext> and StateContext<TState> base
classes, and IOriginator / IMemento for memento snapshots.
public sealed class Door : StateContext<DoorState>
{
public Door() : base(new Closed()) { }
protected override bool CanTransitionTo(DoorState newState) => newState is not Locked || CurrentState is Closed;
}
public abstract class DoorState : State<Door>;
public sealed class Closed : DoorState
{
protected override void OnEnteringStateContext(Door context) => Console.WriteLine("closed");
}
door.StateTransitioned += (_, e) => Console.WriteLine($"{e.PreviousState} → {e.NewState} at {e.TransitionTime}");
door.TransitionToState(new Open());
A transition runs, in order: CanTransitionTo (a refusal throws InvalidOperationException and runs nothing else),
OnStateTransitioning, StateTransitioning, the swap, exit of the previous state, entry of the new state,
OnStateTransitioned, StateTransitioned. No lock is held while user code runs. The swap is an atomic
compare-and-swap against the state the transition started from, made before any state exits: when a concurrent
transition replaced it first, this one throws InvalidOperationException and exits nothing (its pre-swap callbacks may
already have run). The comparison is by reference, so a state replaced and then restored with the same instance is not
detected. An exception thrown by the previous state's exit or by the new state's enter leaves the new state current
(not entered after an exit failure); the post-transition callback and event do not run. A state entered with a context
of the wrong type throws InvalidOperationException. TransitionTime comes from the context's TimeProvider
(override the protected property; TimeProvider.System by default), read when the transition starts.
🧰 Utilities
MIME types
string? type = MimeTypes.GetMimeType("reports/2026.pdf"); // "application/pdf"
if (MimeTypes.TryGetMimeType(path.AsSpan(), out string? mimeType)) { } // allocation-free
MimeTypes.Mappings is the read-only extension → MIME type table (the ASP.NET Core
FileExtensionContentTypeProvider set). Extensions match case-insensitively; a path without an extension (or a
null/empty one) returns null, and invalid path characters do not throw.
Weak-reference cache
MemoryAwareCache<TKey, TValue> holds its values through WeakReference<T> (WeakCacheEntry<T>), so a value no
other code references can be garbage collected. The parameterless cache sweeps collected entries every 5 minutes. With
cleanupInterval and maxAge, the sweep runs every cleanupInterval (TimeSpan.Zero or less: no sweep) and removes
collected entries and entries older than maxAge; a read never returns an entry older than maxAge (measured from
insertion), sweep or not. Sweeps never overlap. The cache is safe for concurrent use; GetOrAdd runs the factory once
per key under concurrent misses (the others wait for its value); a factory that throws stores nothing and the next call
runs it again.
using var cache = new MemoryAwareCache<string, Template>(
cleanupInterval: TimeSpan.FromMinutes(1),
maxAge: TimeSpan.FromMinutes(30));
Template template = cache.GetOrAdd("invoice", key => LoadTemplate(key)); // re-creates a collected value
cache.AddOrUpdate("receipt", receiptTemplate);
bool hit = cache.TryGetValue("invoice", out Template? cached);
cache.Clear();
// Tests: a TimeProvider drives the timer and the entry ages (new MemoryAwareCache<string, Template>(fakeTimeProvider)
// for the default sweep)
using var testCache = new MemoryAwareCache<string, Template>(
TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(30), fakeTimeProvider);
GetOrAdd and AddOrUpdate throw ObjectDisposedException after Dispose; TryGetValue returns false and
Clear does nothing.
Text encryption and password hashing
TextCryptography encrypts text with a passphrase (AES-256-GCM) and hashes passwords (PBKDF2-HMAC-SHA256):
EncryptedValue encrypted = TextCryptography.Encrypt("secret", passphrase);
string plain = TextCryptography.Decrypt(encrypted, passphrase);
string hash = TextCryptography.HashPassword("correct horse"); // store this
bool valid = TextCryptography.VerifyPassword("correct horse", hash); // constant-time comparison
string salt = TextCryptography.GenerateSalt(32); // base64, 1..65535 random bytes
- Encryption. The AES-256 key is derived from the passphrase by PBKDF2-HMAC-SHA256 (600 000 iterations) over a
random salt, and every value gets a random nonce, so equal texts give different values.
EncryptedValueholds theValue(base64 of the format version byte, the nonce, the cipher text and the 16-byte authentication tag) and theSalt; the passphrase is never part of it. The format version fixes the algorithm and the iteration count, so values stay decryptable. Each call derives the key (a fraction of a second): encrypt a few secrets, not every row. A text with a lone surrogate throwsArgumentException.DecryptthrowsCryptographicExceptionwhen the passphrase is wrong or the value or salt was altered or malformed, andArgumentExceptionfor a defaultEncryptedValue. A value or saltEncryptcannot have written (too short, another version, a salt that is not 16 bytes) fails before the key derivation. The platform must support AES-GCM (AesGcm.IsSupported). - Passwords are hashed, not encrypted.
HashPasswordreturnspbkdf2-sha256$<iterations>$<salt>$<hash>(a random 16-byte salt, a 32-byte hash) withDefaultPasswordIterations(600 000, the OWASP recommendation) or the count passed asiterations(MinPasswordIterations, 100 000, to 10 000 000); an empty password throwsArgumentException. Each verification costs as much as the hashing, so a workload that hashes often trades some brute-force resistance for throughput.VerifyPasswordreads the iteration count from the stored hash (so changing the count of new hashes keeps old ones valid) and compares in constant time; a value that is not such a hash (salt under 16 bytes, count above 10 000 000) throwsFormatException. The hash must come from trusted storage.
Random text
string token = TextGenerator.Generate(16); // from TextGenerator.LookupCharacters: A-Z, a-z, 0-9, '-' and '_'
string digits = TextGenerator.Generate(6, "0123456789"); // length 1..65535
Characters are drawn with RandomNumberGenerator.
String formatting
string a = "Total: {0:N2}".StringFormat(CultureInfo.GetCultureInfo("de-DE"), 1234.5); // "Total: 1.234,50"
string b = "{0}-{1}".StringFormat(1.5, 2); // invariant culture: "1.5-2"
string c = "HttpRequestMessage".SplitTypeName(); // "Http Request Message"
StringFormat takes up to six arguments, with or without a culture (invariant by default); a null argument
formats as an empty string. For a template formatted many times, parse it once with CompositeFormat.Parse and call
string.Format(provider, compositeFormat, args).
Object and delegate helpers
bool isNull = value.IsNull;
Order? order = obj.As<Order>(); // null when obj is not an Order
Order required = obj.AsRequired<Order>(); // ArgumentNullException / InvalidCastException
var options = new ExportOptions().When(isDevelopment, o => o.Verbose = true);
// Wrap any failure (except InvalidOperationException and cancellation) in an InvalidOperationException
int value = ((Func<int>)Compute).ThrowInvalidOperationException();
await LoadAsync().ThrowInvalidOperationException();
Disposable base classes
Disposable and DisposableAsync implement the standard dispose pattern. Only the first Dispose /
DisposeAsync call runs the disposal; later and concurrent calls return at once, even when the first one failed.
IsDisposed becomes true once the base Dispose(bool) has run.
public sealed class MyResource : Disposable
{
private readonly FileStream _stream = File.OpenRead("data.bin");
protected override void Dispose(bool disposing)
{
if (disposing)
{
_stream.Dispose();
}
base.Dispose(disposing);
}
}
public sealed class MyAsyncResource : DisposableAsync
{
protected override async ValueTask DisposeAsync(bool disposing)
{
if (disposing)
{
await _connection.DisposeAsync();
}
await base.DisposeAsync(disposing);
}
}
Dates and times persisted with a culture
DateOnlyJsonConverter and TimeOnlyJsonConverter write what System.Text.Json writes (yyyy-MM-dd; HH:mm:ss, with
seven fraction digits when there is a fraction) and read ISO 8601 first, then the date or time format of the culture
given to the constructor: the culture an application used when it persisted its data. Dictionary keys are read and
written the same way, and DateOnly? / TimeOnly? are covered through the converter of the underlying type. A value
that matches neither format throws a JsonException that does not repeat it.
Register them on a dedicated serializer context for the persisted data, before AddXJsonSerializerOptions /
AddXJsonSerializerContext, which register theirs only when none exists, so the HTTP options keep reading dates and
times strictly:
CultureInfo persisted = CultureInfo.GetCultureInfo("fr-FR");
services.AddSingleton<IJsonSerializerContext>(new DefaultJsonSerializerContext(new JsonSerializerOptions
{
TypeInfoResolver = AppJsonContext.Default,
Converters = { new DateOnlyJsonConverter(persisted), new TimeOnlyJsonConverter(persisted) }
}));
Otherwise the event store shares the HTTP options, and the converters would make HTTP input lenient too.
The generic AddXJsonSerializerContext<T>() replaces any registered context (RemoveAll): register the dedicated
context after it, or do not use the generic one alongside it.
🚀 AOT Compatibility
The package contains no RequiresUnreferencedCode or RequiresDynamicCode API and no reflection fallback: an
application behaves the same whether or not it is trimmed or published with Native AOT. Xpandables.Generators
generates at compile time:
- the
IAddServiceregistration (AddXServicesGenerated) and the project's part of the cache-type map (AddX{Assembly}CacheTypes); - the JSON converter of every
Optional<T>your code names (a property, a field, a parameter, a local, a generic argument or a[JsonSerializable(typeof(Optional<X>))]), registered from a module initializer. The built-in value types (int,long,Guid,DateTime, …) need nothing. AnOptional<T>your code never names closed — the memberOptional<T> Itemof a genericPage<T>serialized asPage<Money>— gets no converter: name it once ([JsonSerializable(typeof(Optional<Money>))]) or callOptionalJsonConverters.Register<Money>()at startup.
XTryDecorate builds decorators with ActivatorUtilities, annotated for the trimmer: that is how Microsoft's
dependency injection activates every registered type, so it is as AOT-safe as the container itself.
Diagnostics
| Id | Severity | Reported when |
|---|---|---|
XSR001 |
Warning | A concrete IAddService cannot be constructed by generated code (no accessible parameterless constructor, [Obsolete] on it or a containing type, required members without [SetsRequiredMembers], declared inside a generic type) |
XCT001 |
Error | Two types share a cache type name ([CacheType] or [EventName]) |
XCT002 |
Error | A [CacheType] (or, for an event, [EventName]) name is empty or whitespace |
XOJ001 |
Warning | Optional<T> names a T generated code cannot reach (a private nested or file-local type): register it with OptionalJsonConverters.Register<T>() |
JSON contexts
DefaultJsonSerializerContext requires a TypeInfoResolver on its options and throws InvalidOperationException
at construction when there is none, so JSON never falls back to reflection.
| Context | Types |
|---|---|
OptionalJsonContext |
Optional<T> and T for the built-in value types and string |
ElementCollectionContext |
ElementCollection, ElementEntry, StringValues, array, list and dictionary variants |
ElementEntryContext |
ElementEntry, StringValues, array and list variants |
ElementCollectionContext, ElementEntryContext and OptionalJsonContext write compact JSON.
A Result is an outcome, not a payload: the library declares no JSON metadata for it, and its integrations never write
one (ASP.NET Core writes its value or its problem details; System.Rests reads a response into one). A Native AOT minimal
API lists each Result and Result<T> its endpoints return on its own context all the same: the Request Delegate Generator asks
for the metadata of the declared return type when it builds the endpoint.
JsonTypeInfoExtensions, JsonSerializerOptionsExtensions (GetReadOnlyTypeInfo) and
JsonSerializerContextExtensions (GetRequiredTypeInfo, which throws InvalidOperationException for an unknown
type) are small helpers over JsonTypeInfo resolution.
📦 Package Contents
| Namespace | Types |
|---|---|
System.Results |
Result, Result<TValue>, MergeStrategy, ResultException, ResultExtensions |
System.Optionals |
Optional<T>, Optional, OptionalExtensions, EnumerableExtensions, OptionalJsonConverter<T>, OptionalJsonConverterFactory, OptionalJsonConverters, OptionalJsonContext |
System.Collections |
ElementCollection, ElementEntry, their JSON converters and contexts, ElementCollectionExtensions, HttpHeadersExtensions, ValidationResultExtensions, EnumerableExtensions |
System.States |
IState, IState<T>, State, State<T>, IStateContext, IStateContext<T>, StateContext<T>, StateTransitionEventArgs, IOriginator, IMemento |
System.Composition |
IAddService, AddService |
System.ComponentModel.DataAnnotations |
MultipleValidationException, ValidationExtensions |
System |
Disposable, DisposableAsync, HttpStatusCodeExtensions, IHttpStatusCodeExtension, HttpStatusCodeExtension, ExceptionExtensions, ThrowExceptionExtensions, ObjectExtensions, StringExtensions, IJsonSerializerContext, IJsonSerializerContextExtensions, DefaultJsonSerializerContext, JsonTypeInfoExtensions, JsonSerializerOptionsExtensions, JsonSerializerContextExtensions, CacheTypeAttribute, ICacheTypeResolver, CacheTypeResolver, CorrelationContext, ICorrelationContextAccessor, AsyncLocalCorrelationContextAccessor, CorrelationContextScopeExtensions, RequestScopeAccessor, LazyResolved<T>, MimeTypes, MemoryAwareCache<TKey, TValue>, WeakCacheEntry<T>, TextCryptography, EncryptedValue, TextGenerator, DateOnlyJsonConverter, TimeOnlyJsonConverter |
Microsoft.Extensions.DependencyInjection |
NetServiceCollectionExtensions, IServiceDecoratorExtensions |
📄 License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
<div align="center">
Built with ❤️ using .NET 11
</div>
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Microsoft.Extensions.DependencyInjection (>= 11.0.0)
- Xpandables.Generators (>= 11.0.2)
NuGet packages (15)
Showing the top 5 NuGet packages that depend on Xpandables.Net:
| Package | Downloads |
|---|---|
|
Xpandables.Net.EntityFramework
A utility library in .Net9.0 to easily add patterns such as CQRS |
|
|
Xpandables.Net.DependencyInjection
A utility library in .Net7.0 to easily add dependency injection using the Xpandables.Net library |
|
|
Xpandables.NetCore
A utility library in .Net5.0 to add AspNetCore behaviors to Xpandables.Net. |
|
|
Xpandables.Net.AspNetCore
A utility library in .Net9.0 that adds AspNetCore behaviors to Xpandables.Net |
|
|
Xpandables.Net.Windows
A utility library in .Net5.0 to extend Windows Forms and WPF behaviors. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 11.0.2 | 128 | 12/2/2026 |
| 11.0.1 | 168 | 11/30/2026 |
| 11.0.0 | 176 | 11/29/2026 |
| 9.3.4 | 495 | 4/27/2025 |
| 9.3.2 | 368 | 4/20/2025 |
| 9.3.0 | 399 | 4/14/2025 |
| 9.1.2 | 349 | 3/12/2025 |
| 9.1.0 | 360 | 3/8/2025 |
| 9.0.1 | 290 | 1/19/2025 |
| 9.0.0-rc.1 | 192 | 10/26/2024 |
| 8.1.2 | 355 | 9/12/2024 |
| 8.0.8 | 324 | 6/21/2024 |
| 8.0.6 | 304 | 5/25/2024 |
| 8.0.5 | 323 | 5/18/2024 |
| 8.0.1 | 531 | 2/11/2024 |
| 8.0.0 | 696 | 12/3/2023 |
| 8.0.0-rc.2.1.1 | 236 | 11/12/2023 |
| 8.0.0-rc.2.1 | 216 | 11/6/2023 |
| 8.0.0-rc.2.0 | 214 | 11/5/2023 |
| 7.3.3 | 879 | 5/9/2023 |