Wiaoj.Serialization.Abstractions
0.5.1-alpha
See the version list below for details.
dotnet add package Wiaoj.Serialization.Abstractions --version 0.5.1-alpha
NuGet\Install-Package Wiaoj.Serialization.Abstractions -Version 0.5.1-alpha
<PackageReference Include="Wiaoj.Serialization.Abstractions" Version="0.5.1-alpha" />
<PackageVersion Include="Wiaoj.Serialization.Abstractions" Version="0.5.1-alpha" />
<PackageReference Include="Wiaoj.Serialization.Abstractions" />
paket add Wiaoj.Serialization.Abstractions --version 0.5.1-alpha
#r "nuget: Wiaoj.Serialization.Abstractions, 0.5.1-alpha"
#:package Wiaoj.Serialization.Abstractions@0.5.1-alpha
#addin nuget:?package=Wiaoj.Serialization.Abstractions&version=0.5.1-alpha&prerelease
#tool nuget:?package=Wiaoj.Serialization.Abstractions&version=0.5.1-alpha&prerelease
Wiaoj.Serialization
One serializer abstraction for .NET, with several formats and behaviours side by side in one application. Each configuration is registered under a key type: the API writes camel-case JSON, the cache writes compressed MessagePack, secrets are encrypted with a Wiaoj.Security key ring, and code asks for ISerializer<CacheKey> without knowing which library is behind it.
Packages
| Package | What it adds |
|---|---|
Wiaoj.Serialization.Abstractions |
ISerializer, ISerializer<TKey>, ISerializerKey, the exception types |
Wiaoj.Serialization.DependencyInjection |
AddWiaojSerializer, ISerializationBuilder, the default ISerializer |
Wiaoj.Serialization.SystemTextJson |
UseSystemTextJson: JSON, including IAsyncEnumerable streaming |
Wiaoj.Serialization.MessagePack |
UseMessagePack: compact binary, readable from other languages |
Wiaoj.Serialization.MemoryPack |
UseMemoryPack: compact binary between .NET applications (limits) |
Wiaoj.Serialization.Bson |
UseBson: MongoDB BSON documents |
Wiaoj.Serialization.YamlDotNet |
UseYamlDotNet: YAML |
Wiaoj.Serialization.Compression |
WithGzipCompression, WithBrotliCompression |
Wiaoj.Serialization.Security |
WithEncryption<TKey, TContext>: AES-GCM with a Wiaoj.Security key ring |
Wiaoj.Serialization.Transcoding |
ITranscoder: convert bytes from one registered format to another |
dotnet add package Wiaoj.Serialization.DependencyInjection
dotnet add package Wiaoj.Serialization.SystemTextJson # and any other format you need
Namespaces:
AddWiaojSerializeris inMicrosoft.Extensions.DependencyInjection.- The contracts and every registration method (
Use…,TryUse…,With…,AddTranscoding) are inWiaoj.Serialization. - Each package's own types are in its namespace, for example
Wiaoj.Serialization.Security.DecryptionFailedExceptionandWiaoj.Serialization.Transcoding.ITranscoder.
Quick start
1. Define keys
A key is a marker type that names one configuration.
using Wiaoj.Serialization;
public readonly struct ApiKey : ISerializerKey;
public readonly struct CacheKey : ISerializerKey;
2. Register
builder.Services.AddWiaojSerializer(serializers => {
// Keyless: resolved as the non-keyed ISerializer
serializers.UseSystemTextJson(new JsonSerializerOptions(JsonSerializerDefaults.Web));
serializers.UseSystemTextJson<ApiKey>();
serializers.UseMessagePack<CacheKey>()
.WithBrotliCompression(CompressionLevel.Fastest);
});
AddWiaojSerializer() without a callback returns the builder instead, for one or two calls.
3. Use
public sealed class ProductCache(ISerializer<CacheKey> serializer, IDistributedCache cache) {
public Task SetAsync(Product product, CancellationToken ct) =>
cache.SetAsync($"product:{product.Id}", serializer.Serialize(product), ct);
}
The non-keyed ISerializer is the keyless serializer when one is registered, otherwise the only registered serializer. With several keyed serializers and no keyless one there is none: GetService<ISerializer>() returns null.
Registering the same key twice throws.
TryUse…(every format) registers only when the key is free.Replace…(SystemTextJson and MemoryPack) swaps an existing registration.
Input, output and ownership
- With the built-in adapters,
Serialize<T>(value)returns an ownedbyte[];SerializeToStringreturns a materializedstring. Text is not necessarily the format’s human-readable representation: binary codecs expose Base64 and encryption uses its compact envelope. Serialize<T>(writer, value)writes to a caller-ownedIBufferWriter<byte>. This avoids requiring a returned array, not necessarily temporary storage. AReadOnlySequence<byte>can be non-contiguous; adapters may copy it. Keep input memory valid for the duration of the read.- The synchronous read APIs accept
byte[],string, orReadOnlySequence<byte>, with either a generic target or an explicit runtimeType.SerializeToStringand the async stream read/write APIs also have explicit runtime-type overloads; the sync byte-array and buffer-writer writes are generic.TryDeserializeandTryDeserializeAsyncare generic, and a successful nullable read can returnnull. - Stream overloads borrow the caller’s source or destination. Keep it open until the operation completes, or until you dispose a streaming enumerator. Do not assume that an async signature implies incremental parsing, that a failure restores the original stream position, or that an output stream can roll back a partial write.
| Built-in adapter | Text | Caller writer / sequence read | Stream path |
|---|---|---|---|
| System.Text.Json | JSON | Uses Utf8JsonWriter; reads the sequence with Utf8JsonReader without flattening it in the adapter. |
Delegates single-value reads/writes to STJ. The separate experimental JSON array API yields elements incrementally. |
| MessagePack | Base64 of MessagePack bytes | Passes writer and sequence to MessagePack. | Delegates to MessagePack’s stream helpers, which can stage output and buffer input; this is not an incremental element API. |
| MemoryPack | Base64 of MemoryPack bytes | Passes writer and sequence to MemoryPack. | Delegates to MemoryPack’s stream helpers, which can buffer input; this is not an incremental element API. |
| BSON | Base64 of BSON bytes | Writes an intermediate array to the writer; flattens sequence input. | Stages writes; the MongoDB BSON reader performs synchronous reads behind the async API. Do not assume a nonseekable BSON stream works. |
| YamlDotNet | YAML | Writes an intermediate UTF-8 array to the writer; flattens only multi-segment input before text decoding. | Uses a text writer; reads the entire decoded text before parsing. |
| Compression | Base64 of compressed bytes | Writes an intermediate compressed array; flattens sequence input. | Stages serialized output before compressing. Unlimited reads pass the decompression stream to the inner codec; limited reads stage the decoded payload through EOF before parsing. |
| Encryption | Compact encrypted envelope | Writes an intermediate encrypted array; flattens sequence input. | Buffers the message; authentication precedes exposing the plaintext to the inner codec. |
These are adapter-level choices, not zero-allocation or memory bounds for codec internals. Treat the result of Try as a codec-specific read outcome, not a blanket exception shield. See the decorator and Native AOT notes below for the boundaries tested here.
Behaviours
With… methods wrap the serializer in a decorator, in the order they are called. Compressing and then encrypting runs as follows:
value → format serializer → compression → encryption → bytes
Compress before you encrypt: ciphertext does not compress.
Compression
serializers.UseSystemTextJson<LogKey>().WithGzipCompression();
serializers.UseMessagePack<CacheKey>().WithBrotliCompression(CompressionLevel.Fastest);
Install the adapter and the format package if they are not already referenced:
dotnet add package Wiaoj.Serialization.Compression
dotnet add package Wiaoj.Serialization.SystemTextJson
The ceiling is opt-in, and existing registrations remain unlimited. Configure it on your existing service collection:
using System.IO.Compression;
using Microsoft.Extensions.DependencyInjection;
using Wiaoj.Serialization;
services.AddWiaojSerializer(serializers =>
serializers.UseSystemTextJson().WithGzipCompression(
CompressionLevel.Optimal, maxDecompressedBytes: 1_048_576));
The ceiling is decode-only for both Gzip and Brotli: it does not restrict what the serializer writes. A valid write can produce a payload which the same bounded registration subsequently rejects on read. An exact fit succeeds.
A limited stream read counts decoded bytes through the platform decoder's EOF before invoking the inner serializer, even if that serializer would stop early. The ceiling bounds the logical decoded payload retained for one read, not total memory, pooled buffer capacity, codec working memory, inner serializer allocations, or concurrent operations. It is not a compressed-input, CPU, or network-time limit. It retains the platform's existing member/trailer handling, not stronger validation. Select a ceiling and retain the caller's cancellation policy.
Compression format errors reported by the platform codec, malformed serialized data and invalid Base64 return false from compression's TryDeserialize* methods. A valid JSON null for a nullable target returns success with a null result. Cancellation, caller stream errors, configuration and missing metadata errors are not format failures. A limit violation throws DecompressedByteLimitExceededException (even for a Try method). Compression owns its codec streams and pooled buffers but does not close the caller's input or output stream. The default unlimited async read still streams into the inner serializer.
Encryption with a Wiaoj.Security key ring
Encrypts everything a serializer writes with the ISecretProtector<TContext> of a Wiaoj.Security context. That gives authenticated AES-GCM, keys held in your key store under a master key, and rotation. Data written under an older key stays readable while the key ring still holds that key.
public readonly struct SecureDataKey : ISerializerKey;
public sealed class SecureDataContext : ISecretContext;
builder.Services.AddWiaojSecurity()
.AddEnvironmentMasterKey()
.AddEntityFrameworkKeyStore<AppDbContext>()
.AddManagedProtector<SecureDataContext>();
builder.Services.AddWiaojSerializer(serializers => serializers
.UseSystemTextJson<SecureDataKey>()
.WithEncryption<SecureDataKey, SecureDataContext>());
- Bytes are the key version (4 bytes, big-endian) followed by the ciphertext. Text is the
EncryptedSecretcompact form,v{version}.{blob}. - Malformed encrypted envelopes, unsuccessful authentication, and missing decryption keys throw
DecryptionFailedExceptionon throwing reads. Encryption’sTryDeserialize*methods returnfalsefor those failures and for malformed inner data. They do not turn cancellation or arbitrary protector/configuration exceptions into a negative result. - Encryption is not deterministic. The same value gives different bytes each time, so encrypted output cannot be used as a cache key or compared for equality.
Transcoding
Convert bytes from one registered format to another, for example to re-encode cached JSON as MessagePack:
serializers.AddTranscoding().UseSystemTextJson<JsonKey>();
serializers.UseMessagePack<PackKey>();
byte[] pack = transcoder.From<JsonKey>(jsonBytes).To<PackKey, Order>();
From borrows jsonBytes until To runs. Do not modify or return a pooled source array during that interval. To materializes the model and returns destination bytes owned by the caller; it is not a streaming byte-to-byte conversion.
Streaming a JSON array
SystemTextJsonSerializer<TKey> also implements the experimental IAsyncEnumerableSerializer (WS0001). Its enumerable overload writes one JSON array, and DeserializeAsyncEnumerable<T> yields the elements of one JSON array. This is not JSON Lines or a sequence of standalone JSON documents. Opt in to WS0001 explicitly if you use this interface:
#pragma warning disable WS0001 // This application opts into the experimental API.
if(serializer is IAsyncEnumerableSerializer streaming) {
await foreach(Product? product in streaming.DeserializeAsyncEnumerable<Product>(stream, ct)) {
// ...
}
}
#pragma warning restore WS0001
Plain STJ has regression coverage for a nullable array item, stopping enumeration before requesting an unavailable tail, caller cancellation during a pending read, and a malformed array raising DeserializationFormatException. The caller stream stays open in these tests. The malformed-array test does not promise how many items are yielded before the error. Other formats and STJ wrapped in compression or encryption do not implement this interface.
System.Text.Json with Native AOT
Register the existing source-generated context for the serializer key, with no fallback resolver needed:
services.AddWiaojSerializer(serializers =>
serializers.UseSystemTextJson<LogKey>(MyJsonContext.Default));
Add each serialized type (including runtime types used by the polymorphic overloads) to the context via [JsonSerializable]. Missing metadata is a configuration failure, not malformed JSON: serialization reports UnsupportedTypeException; the generic and synchronous runtime-type deserialization paths surface the missing-metadata NotSupportedException even through a Try API. The underlying async runtime-type overload reports UnsupportedTypeException. The complete Linux x64 package-only consumer includes its project (PublishAot=true, JsonSerializerIsReflectionEnabledByDefault=false), source-generated context and runner. The workflow packs local NuGet candidates, publishes the consumer outside the repository and executes the resulting native binary. It checks normal, malformed, null and missing-metadata JSON cases plus direct and bounded Gzip/Brotli reads, including the distinct byte-limit exception. This verifies the packaged STJ + DI + Compression composition on Linux x64 with registered metadata. It does not cover the experimental array API, runtime key lookup under AOT, arbitrary model types, other serializer backends, or other platforms.
Formats
YAML and BSON
serializers.UseYamlDotNet<ConfigKey>(yaml => yaml.WithNamingConvention(CamelCaseNamingConvention.Instance));
serializers.UseBson<MongoKey>();
BSON needs a representation configured before it can write a Guid, and it writes a DateTimeOffset as an array. If your types use either, configure MongoDB's serializers for them.
MemoryPack
UseMemoryPack<TKey>() writes a compact binary format with very little work per value, but it only suits data exchanged between .NET applications:
- For custom source-generated models, use
[MemoryPackable]on apartialtype. Built-in supported types such asstringdo not need their own generated model. - Under the MemoryPack versioning rules, appending a member to a supported default object model lets a new reader read old payloads, not the reverse; do not remove, reorder, or change the type of an existing positional member.
[MemoryPackable(GenerateType.VersionTolerant)]with explicit, stable[MemoryPackOrder]values permits adding and removing members. Never reuse a removed order value or change an existing member's order or type in place; introduce a new member or migrate the persisted data. Verify the required old/new directions on the actual model; the shared fixture does not certify schema evolution. - Cross-language interoperability is not tested here. Upstream supports TypeScript code generation; prefer a format already verified with both clients, such as JSON or MessagePack if your interoperability tests cover it.
Tested contracts
The shared contract tests exercise representative byte, text, caller-writer, single- and multi-segment sequence, and stream round trips across the built-in formats and tested decorator compositions. They use the generic and explicit Type paths where the contract offers both, and verify representative bad data on throwing and Try paths. Individual tests cover additional ownership, cancellation and null cases; they do not make every codec’s read behavior identical.
The package wire baseline records separately packed old/new fixtures and their scope. See Compression for the opt-in decode limit and Native AOT for the narrower package-only proof. To add a format or decorator, derive a fixture from SerializerContractTests and add focused tests for semantics that differ.
Contributing
See CONTRIBUTING.md. Licensed under MIT; see LICENSE.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- No dependencies.
NuGet packages (14)
Showing the top 5 NuGet packages that depend on Wiaoj.Serialization.Abstractions:
| Package | Downloads |
|---|---|
|
Wiaoj.Serialization.DependencyInjection
ASP.NET Core dependency injection integration for Wiaoj Serialization. |
|
|
Wiaoj.Serialization.SystemTextJson
High-performance System.Text.Json implementation for Wiaoj Serialization with configurable options and telemetry support. |
|
|
Tyto.Abstractions
Package Description |
|
|
Tyto
Package Description |
|
|
Wiaoj.Ddd.EntityFrameworkCore
EF Core integration for Wiaoj DDD, providing Transactional Outbox, Audit Logging, and Domain Event Dispatching interceptors. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.5.2-alpha | 0 | 12/6/2026 |
| 0.5.1-alpha | 0 | 12/6/2026 |
| 0.5.0-alpha.1 | 0 | 12/5/2026 |
| 0.4.2-alpha.2 | 75 | 12/3/2026 |
| 0.4.2-alpha.1 | 100 | 12/2/2026 |
| 0.4.1-alpha.3 | 120 | 11/30/2026 |
| 0.4.1-alpha.2 | 125 | 11/29/2026 |
| 0.4.1-alpha.1 | 133 | 11/28/2026 |
| 0.4.0-alpha.5 | 147 | 11/27/2026 |
| 0.4.0-alpha.4 | 131 | 11/15/2026 |
| 0.4.0-alpha.3 | 126 | 11/4/2026 |
| 0.4.0-alpha.1 | 121 | 10/30/2026 |
| 0.3.0-alpha.1 | 2,936 | 10/5/2026 |
| 0.2.0-alpha.3 | 123 | 9/24/2026 |
| 0.2.0-alpha.2 | 118 | 9/24/2026 |
| 0.2.0-alpha.1 | 124 | 9/24/2026 |
| 0.1.0-alpha.9 | 324 | 9/21/2026 |
| 0.1.0-alpha.8 | 126 | 9/21/2026 |
| 0.1.0-alpha.7 | 2,505 | 9/18/2026 |
| 0.1.0-alpha.6 | 124 | 9/16/2026 |