CoreEx 4.1.0

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

CoreEx

The foundational CoreEx package providing the core runtime primitives, patterns, and abstractions used across all other CoreEx libraries and consuming services.

Overview

CoreEx is the shared kernel of the CoreEx framework. It defines the types that all other packages depend on and that consuming applications interact with every day: semantic exception types, execution context, railway-oriented result types, entity contracts, mapping, JSON utilities, hosting infrastructure, caching abstractions, localization, and more.

The package is deliberately non-opinionated — nothing forces a particular architectural style and every capability is opt-in. Teams can adopt individual namespaces incrementally, composing only what they need without taking on the full framework surface area at once.

All other CoreEx packages (CoreEx.Events, CoreEx.Database, CoreEx.AspNetCore, etc.) depend on this package, making it the natural starting point when working with the CoreEx ecosystem.

Motivation

  • Reduce boilerplate — recurring patterns such as exception-to-HTTP-status mapping, entity identity, ETag handling, and audit change-log tracking are defined once and reused everywhere rather than reimplemented per project.
  • Standardize errors — a rich hierarchy of semantic exception types with built-in HTTP status codes and structured error payloads removes the need for bespoke error-handling middleware.
  • Explicit, expected errors — the Result/Result<T> types bring railway-oriented programming to service code, allowing known business errors to be propagated without the overhead and noise of exceptions.
  • Execution context — a consistent, AsyncLocal-based ambient context carries user identity, tenant, timestamps, and operation type across the full call chain without threading them explicitly through every method signature.
  • Composability — DI registration attributes, invoker tracing, and host-settings primitives are intentionally thin so they integrate into any host model without dictating structure.

Key capabilities

  • 🚨 Semantic exceptions: A hierarchy of typed exceptions (ValidationException, NotFoundException, BusinessException, ConcurrencyException, etc.) each with a pre-mapped HTTP status code, structured error type, and configurable logging enablement.
  • 🔐 Execution context: An AsyncLocal-scoped ExecutionContext that carries user identity (AuthenticationUser), tenant ID, operation type, request timestamp, and arbitrary attributes throughout the lifetime of a request.
  • 🚂 Railway-oriented results: Result and Result<T> value types that represent success or a typed error without throwing, enabling functional pipeline-style error propagation for expected business outcomes.
  • 📦 Entity contracts: Interfaces and types for identifiers (IIdentifier<T>), ETags (IETag), audit change logs (IChangeLog), composite keys (CompositeKey), and entity cleaning/transformation — used as the common contract shape across all CoreEx layers.
  • 🗺️ Explicit mapping: Uni- and Bi-directional mapper base classes and a Mapper utility for propagating standard contract properties (identity, ETags, change logs, tenant, partition) between source and destination types without a reflection-heavy mapping library.
  • 🔄 JSON utilities: RFC 7396 JSON Merge Patch (JsonMergePatch), include/exclude JSON property filtering (JsonFilter), and custom converters for common CoreEx types.
  • 💉 DI lifetime attributes: [ScopedService], [SingletonService], and [TransientService] attributes that mark implementation types for automatic discovery and registration via AddDynamicServicesUsing<T>.
  • ⏱️ Hosting and work orchestration: Base classes for timer-driven and synchronized hosted services, plus WorkOrchestrator for tracking long-running distributed work states with pluggable storage.
  • ⚡ Caching abstractions: IHybridCache and ICacheKeyProvider decouple cache consumption from provider implementation, supporting both in-process and distributed cache strategies.
  • 🌐 Localization: LText and TextProvider provide a lightweight, key-based localization abstraction used throughout validation messages, exception text, and reference data.
  • 🃏 Wildcard parsing: Wildcard provides standardized * and ? wildcard parsing, validation, and Regex compilation for consistent wildcard-based filtering.
  • 🏷️ Reference data interfaces: Core IReferenceData, IReferenceDataCollection, and ReferenceDataOrchestrator types establish the reference data contract used by CoreEx.RefData and data-layer packages.
  • 📐 Schema versioning: SchemaAttribute and Schema utilities for associating a semantic version with entity types, supporting schema-aware messaging and validation.

Key types

Type Description
ExecutionContext AsyncLocal-scoped ambient context carrying user identity, tenant ID, operation type, timestamp, and attributes for the lifetime of a request.
Result Value type representing a successful or failed operation with no return value; the basis of railway-oriented programming in CoreEx.
Result<T> Value type representing a successful operation with a value, or a typed error — used for functional pipeline-style error propagation.
DataConsistencyException Non-error exception used to signal a potential data consistency issue without treating it as an application error.
PrecisionTimeProvider TimeProvider implementation that truncates timestamps to a configurable fractional-second precision for database compatibility.
OperationType Enum representing the CRUD operation type (Get, Create, Update, Delete, Query) carried on the ExecutionContext.
ExtendedException Abstract base for all CoreEx semantic exceptions; provides HTTP status, error type, error code, detail, and configurable logging.
IExtendedException Interface defining the extended exception contract: StatusCode, ErrorType, ErrorCode, IsError, and ShouldBeLogged.

See the Extended Exceptions section below for the full list of semantic exception types.

Validating HTTP response values

HTTP success and JSON deserialization do not guarantee a valid dependency response. Use WithValidator with a CoreEx.Validation.IValidator<T> to opt into response-contract validation:

using var response = await _httpClient.GetAsync($"api/customers/{Uri.EscapeDataString(id)}", ct).ConfigureAwait(false);
return await response.WithValidator(customerValidator).ToResultAsync(ct).ConfigureAwait(false);

The typed wrapper reuses the existing response converters and validates only successful, non-null deserialized values. It returns the validation result's Value, including replacements or normalization. ToResultAsync requires a non-null value both before and after validation; ToResultOrDefaultAsync allows null and skips validation when the response has no value. GetValueAsync and GetValueOrDefaultAsync provide the throwing equivalents. All four methods accept optional JSON serializer options and a cancellation token.

Reported validation errors become HttpRequestException failures with the validation exception as the inner exception, preserving structured messages. ToResult* returns these failures; GetValue* throws them. Under standard CoreEx API exception handling, these are internal 500 errors, not caller 400 validation errors. The exception's upstream status is diagnostic context, not the status returned to the caller. Outer messages do not contain the response body. Existing HTTP/ProblemDetails handling is unchanged; cancellation, deserialization exceptions, and unexpected exceptions thrown by a validator still propagate.

Use a response-specific validator rather than assuming create/update rules apply to read responses. For small client-only rules, prefer a private static readonly Validator<T> configured once with Validator.Create<T>().HasProperty(...) from the CoreEx.Validation package inside the Infrastructure client:

private static readonly Validator<Customer> _validator = Validator.Create<Customer>()
    .HasProperty(x => x.Email, c => c.Mandatory().Email());

// Inside the asynchronous HTTP client method.
using var response = await _httpClient.GetAsync($"api/customers/{Uri.EscapeDataString(id)}", ct).ConfigureAwait(false);
return await response.WithValidator(_validator).ToResultAsync(ct).ConfigureAwait(false);

Extract a colocated validator only for substantial rules or genuine reuse. Validate consumed fields rather than requiring every DTO property or matching identifiers by default. Configure shared rules once without captured request state or scoped dependencies, and test inline rules through client unit tests rather than exposing them solely for testing. Invalid responses must not be cached. See the Customers client sample for a complete implementation. Validators can normalize values or perform I/O, so consider their effects explicitly. The wrapper does not own or dispose the response, cache validation results, or support concurrent response consumption. Keep responsibility for disposing the response at the call site. Like the underlying converters, a terminal operation consumes the content stream; creating a wrapper does not buffer the body for repeated reads.

Errors vs Exceptions

CoreEx distinguishes between expected and unexpected errors:

Aspect Errors (Expected) Exceptions (Unexpected)
Use For Validation failures, business rules, "not found" System failures, infrastructure errors
Types CoreEx semantic exceptions (implement IExtendedException) Standard .NET, and non-semantic, exceptions
Benefits Explicit error handling Rich diagnostics (stack traces)
Example Customer not found Database connection timeout

Extended Exceptions

Semantic (error-oriented) exception types with automatic HTTP status mapping:

Exception Description HTTP Status Error Type
AuthenticationException User not authenticated. 401-Unauthorized authentication
AuthorizationException User lacks permissions. 403-Forbidden authorization
BusinessException Business rule violation (message shown to consumer). 400-Bad Request business
ConcurrencyException Data concurrency conflict (ETag mismatch). 412-Precondition Failed concurrency
ConflictException Data conflict (e.g., identifier already exists on create). 409-Conflict conflict
DuplicateException Duplicate value (e.g., unique code already in use). 409-Conflict duplicate
NotFoundException Entity not found. 404-Not Found not-found
TransientException Transient failure (retry candidate). 503-Service Unavailable transient
ValidationException Validation failure with message collection. 400-Bad Request validation

All inherit from ExtendedException<TSelf> implementing IExtendedException.

Additionally, these support With*-style methods to add additional context that is added to the resulting ProblemDetails:

throw new BusinessException($"Product '{movement.ProductId}' does not have sufficient quantity on hand.")
    .WithErrorCode("insufficient-quantity")
    .WithKey(movement.ProductId);

The above would result in the following ProblemDetails:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "Product \u002700000001-0000-0000-0000-000000000000\u0027 does not have sufficient quantity on hand.",
  "status": 400,
  "traceId": "00-a8e8623ef74c2b53820d0ff5d799850d-df28b0bc787429f5-01",
  "errorType": "business",
  "errorCode": "insufficient-quantity",
  "key": "00000001-0000-0000-0000-000000000000"
}

Namespaces

Namespace Description Documentation
CoreEx.Caching IHybridCache abstraction and ICacheKeyProvider for decoupled local and/or distributed caching. 📖 README
CoreEx.Data Lightweight data-access primitives: paging, query arguments, partition keys, tenant IDs, logical deletion, and ItemsResult<T>. 📖 README
CoreEx.DependencyInjection Service lifetime attributes ([ScopedService], [SingletonService], [TransientService]) for attribute-driven DI registration. 📖 README
CoreEx.Entities Entity contract interfaces and types: identifiers, ETags, change logs, composite keys, string transforms, and entity cleaning. 📖 README
CoreEx.Globalization TextInfoCasing and globalization extensions for culture-aware string casing transformations. 📖 README
CoreEx.HealthChecks Health check extensions and HealthCheckTags constants for standardizing CoreEx service health reporting. 📖 README
CoreEx.Hosting Timer and synchronized hosted service base classes, HostSettings, WorkOrchestrator, and distributed work state tracking. 📖 README
CoreEx.Http HTTP primitives: ProblemDetails, IdempotencyKeyHandler, HttpNames, and HTTP request/response extensions. 📖 README
CoreEx.Invokers Invocation pipeline abstractions providing automatic OpenTelemetry tracing and structured logging around service operations. 📖 README
CoreEx.Json JSON Merge Patch (RFC 7396), JSON property filtering, and custom converters for CoreEx entity types. 📖 README
CoreEx.Localization LText localization-agnostic text value and TextProvider for key-based message resolution. 📖 README
CoreEx.Mapping Explicit bi-directional mapper base classes, Mapper standard-property utilities, and IConverter value converters. 📖 README
CoreEx.Metadata RuntimeMetadata and IPropertyRuntimeMetadata for compile-time and reflection-based property introspection on contract types. 📖 README
CoreEx.RefData Core reference data interfaces, ReferenceDataOrchestrator, and provider abstractions consumed by CoreEx.RefData. 📖 README
CoreEx.Results Result and Result<T> railway-oriented types with a full suite of functional extension methods. 📖 README
CoreEx.Schemas SchemaAttribute and Schema utilities for associating semantic version metadata with entity types. 📖 README
CoreEx.Security AuthenticationUser record and AuthenticationType enum representing the authenticated user on the ExecutionContext. 📖 README
CoreEx.Text SentenceCase utility for converting identifier-style strings into human-readable sentence-case text. 📖 README
CoreEx.Validation Lightweight validation interfaces (IValidator<T>, MultiValidator) used as the validation contract across CoreEx. 📖 README
CoreEx.Wildcards Wildcard parser, validator, and Regex compiler for standardized * and ? wildcard-based text matching. 📖 README
  • CoreEx.AspNetCore - ASP.NET Core integration: WebApi HTTP helpers, IExtendedException middleware, and ExecutionContext middleware binding.
  • CoreEx.Validation - Full validation rule engine built on top of the IValidator<T> contract defined in this package.
  • CoreEx.Events - Event publishing and subscribing built on top of the ExecutionContext, Result, and entity contracts from this package.
  • CoreEx.Database - Database access layer built on the data primitives (PagingArgs, QueryArgs, IIdentifier) defined here.
  • CoreEx.EntityFrameworkCore - Entity Framework Core integration consuming the entity contracts and mapping types from this package.
  • CoreEx.RefData - Full reference data implementation extending the IReferenceData and ReferenceDataOrchestrator types defined here.
  • CoreEx.UnitTesting - Test helpers and fluent assertion extensions targeting the types and patterns from this package. (test only)

AI Usage Guide

An AGENTS.md file is included with this package. AI coding assistants (GitHub Copilot, Claude, Cursor, etc.) that support workspace-injected package documentation will automatically surface concise usage guidance, code examples, and Do Not rules for this package without requiring a local CoreEx checkout.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (23)

Showing the top 5 NuGet packages that depend on CoreEx:

Package Downloads
CoreEx.Database

Core .NET extensions and abstractions for the development of backend services.

CoreEx.Newtonsoft

CoreEx .NET Newtonsoft Extensions.

CoreEx.Azure

CoreEx .NET Azure Extensions.

CoreEx.Validation

Core .NET extensions and abstractions for the development of backend services.

CoreEx.Database.SqlServer

Core .NET extensions and abstractions for the development of backend services.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on CoreEx:

Repository Stars
Avanade/Beef
The Business Entity Execution Framework (Beef) framework, and the underlying code generation, has been primarily created to support the industrialization of API development.
Version Downloads Last Updated
4.1.0 0 10/12/2026
4.0.0 359 9/21/2026
4.0.0-preview-5 374 8/23/2026
4.0.0-preview-4 352 8/21/2026
4.0.0-preview-3 433 8/4/2026
4.0.0-preview-2 352 7/10/2026
4.0.0-preview-1 340 6/20/2026
3.31.0 14,168 2/1/2025
3.30.2 949 12/11/2024
3.30.1 916 12/9/2024
3.30.0 9,319 11/21/2024
3.29.0 9,472 11/19/2024
3.28.0 961 11/9/2024
3.27.3 1,642 10/23/2024
3.27.2 887 10/17/2024
3.27.1 1,212 10/15/2024
3.27.0 1,928 10/11/2024
3.26.0 947 10/3/2024
3.25.6 1,553 10/2/2024
3.25.5 1,050 9/25/2024
Loading failed