Xpandables.Primitives
10.0.1
See the version list below for details.
dotnet add package Xpandables.Primitives --version 10.0.1
NuGet\Install-Package Xpandables.Primitives -Version 10.0.1
<PackageReference Include="Xpandables.Primitives" Version="10.0.1" />
<PackageVersion Include="Xpandables.Primitives" Version="10.0.1" />
<PackageReference Include="Xpandables.Primitives" />
paket add Xpandables.Primitives --version 10.0.1
#r "nuget: Xpandables.Primitives, 10.0.1"
#:package Xpandables.Primitives@10.0.1
#addin nuget:?package=Xpandables.Primitives&version=10.0.1
#tool nuget:?package=Xpandables.Primitives&version=10.0.1
System.Primitives
Core primitives and utilities for .NET applications. Zero dependencies, foundational abstractions.
Overview
System.Primitives provides foundational abstractions and utilities used throughout the Xpandables.Net ecosystem. It includes strongly-typed primitive wrappers (Value Objects), state management patterns, memory-aware caching, element collections, and essential extension methods.
Built for .NET 10 with zero external dependencies.
Features
Primitives (Value Objects)
IPrimitive— Base primitive interfaceIPrimitive<TValue>— Typed primitive with valueIPrimitive<TPrimitive, TValue>— Strongly-typed primitive with factory methodsPrimitiveJsonConverterAttribute— JSON serialization support for primitives
Collections
ElementCollection— Key-value collection with O(1) lookupElementEntry— Single entry with key and valuesElementCollectionExtensions— Extension methods for collectionsEnumerableExtensions— LINQ extensionsQueryableEmpty<T>— Empty queryable implementationValidationResultExtensions— Convert validation results to collectionsHttpHeadersExtensions— Convert HTTP headers to collections
State Pattern
IState— State interfaceIStateContext— State context for state machinesIMemento— Memento pattern for state snapshotsIOriginator— Originator for memento patternStateContext— Default state context implementationState— Base state implementation
Caching
MemoryAwareCache<TKey, TValue>— Cache with GC pressure monitoring and weak referencesWeakCacheEntry<T>— Weak reference cache entryICacheTypeResolver— Type resolver for cached itemsCacheTypeResolver— Default type resolver
Disposable Helpers
Disposable— Base class for IDisposableDisposableAsync— Base class for IAsyncDisposable
Extension Methods
StringExtensions— String manipulation and formattingObjectExtensions— Object null checks and type conversionExceptionExtensions— Exception details and HTTP status mappingHttpStatusCodeExtensions— HTTP status helpers (Title, Detail, IsSuccess)JsonSerializerExtensions— JSON serialization helpersThrowExceptionExtensions— Fluent exception throwing
Dependency Injection
IAddService— Service registration interfaceIServiceDecoratorExtensions— Decorator pattern for DIExportOptions— MEF-style export optionsStaticConfiguration— Static configuration utilitiesLazyResolved<T>— Lazy service resolution
Installation
dotnet add package Xpandables.Primitives
Quick Start
Strongly-Typed Primitives
using System;
[PrimitiveJsonConverter<Email, string>]
public readonly record struct Email : IPrimitive<Email, string>
{
public required string Value { get; init; }
public static Email Create(string value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value);
if (!value.Contains('@'))
throw new ArgumentException("Invalid email format");
return new Email { Value = value.ToLower() };
}
public static string DefaultValue => string.Empty;
public static bool TryParse(
string? s, IFormatProvider? provider, out Email result)
{
if (s is not null && s.Contains('@'))
{
result = Create(s);
return true;
}
result = default;
return false;
}
public string ToString(string? format, IFormatProvider? provider) =>
Value;
public int CompareTo(Email other) =>
string.Compare(Value, other.Value, StringComparison.Ordinal);
public int CompareTo(object? obj) =>
obj is Email other ? CompareTo(other) : 1;
public bool Equals(Email other) => Value == other.Value;
}
// Usage
Email email = Email.Create("john@example.com");
string emailStr = email.Value; // "john@example.com"
Element Collections
using System.Collections;
// Create a collection
var collection = ElementCollection.With("key1", "value1", "value2")
+ new ElementEntry("key2", "value3");
// Access entries
foreach (var entry in collection)
{
Console.WriteLine($"{entry.Key}: {string.Join(", ", entry.Values)}");
}
// Lookup by key (O(1))
if (collection.TryGetValue("key1", out var values))
{
Console.WriteLine($"Found: {values}");
}
Memory-Aware Cache
using System.Cache;
// Cleanup every 5 mins, items expire after 1 hour (defaults)
var cache = new MemoryAwareCache<string, User>();
// Get existing or create new
User user = cache.GetOrAdd("user:123", key => LoadUser(key));
// Add or update
cache.AddOrUpdate("user:456", new User { Id = 456, Name = "Jane" });
// Try retrieve
if (cache.TryGetValue("user:123", out var cachedUser))
{
Console.WriteLine($"Found: {cachedUser.Name}");
}
// Items use weak references — automatically collected under GC pressure
HttpStatusCode Extensions
using System.Net;
var status = HttpStatusCode.BadRequest;
bool isSuccess = status.IsSuccess; // false
bool isFailure = status.IsFailure; // true
bool isValidation = status.IsValidationProblem; // true
string title = status.Title; // "Bad Request"
string detail = status.Detail; // Description text
Exception Extensions
try
{
// Some operation
}
catch (Exception ex)
{
// Get full message including inner exceptions
string fullMessage = ex.GetFullExceptionMessage();
// Convert to ElementCollection for structured error data
ElementCollection entries = ex.GetElementEntries();
// Get the appropriate HTTP status code
HttpStatusCode statusCode = ex.GetHttpStatusCode();
}
🔧 Disposable Helpers
Synchronous Disposable
public class MyResource : Disposable
{
private readonly Stream _stream;
public MyResource(Stream stream) => _stream = stream;
protected override void Dispose(bool disposing)
{
if (disposing)
{
_stream?.Dispose();
}
base.Dispose(disposing);
}
}
Async Disposable
public class MyAsyncResource : DisposableAsync
{
private readonly DbConnection _connection;
public MyAsyncResource(DbConnection connection)
=> _connection = connection;
protected override async ValueTask DisposeAsync(bool disposing)
{
if (disposing)
{
await _connection.CloseAsync();
await _connection.DisposeAsync();
}
await base.DisposeAsync(disposing);
}
}
Core Types
| Type | Description |
|---|---|
IPrimitive<TPrimitive, TValue> |
Strongly-typed value object |
ElementCollection |
Key-value collection |
IStateContext |
State machine context |
MemoryAwareCache<TKey, TValue> |
Weak-reference cache with auto-cleanup |
Disposable / DisposableAsync |
Disposable base classes |
✅ Best Practices
- Use primitives for domain concepts — Email, Money, ProductId, etc.
- Validate in
Create()method — Fail fast with clear exceptions - Make primitives
readonly record struct— Stack allocation, value semantics - Decorate with
PrimitiveJsonConverter— Automatic JSON serialization - Keep primitives simple — Single responsibility, no complex business logic
- Use
Disposable/DisposableAsync— Consistent dispose pattern implementation
📚 Related Packages
- Xpandables.Validation — Specification pattern and validation
- Xpandables.Optionals — Optional/Maybe monad
- Xpandables.Results — Result pattern types
📄 License
Apache License 2.0 — Copyright © Kamersoft 2025
| 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. |
-
net10.0
- Microsoft.Extensions.Configuration (>= 10.0.3)
- Microsoft.Extensions.Configuration.EnvironmentVariables (>= 10.0.3)
- Microsoft.Extensions.Configuration.Json (>= 10.0.3)
- Microsoft.Extensions.DependencyInjection (>= 10.0.3)
- Microsoft.Extensions.Primitives (>= 10.0.3)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on Xpandables.Primitives:
| Package | Downloads |
|---|---|
|
Xpandables.Results
Result pattern implementation. |
|
|
Xpandables.Composition
Composition classes. |
|
|
Xpandables.Entities.Data
IRepository EntityFramework implementation. |
GitHub repositories
This package is not used by any popular GitHub repositories.