Xpandables.Generators
11.0.0
dotnet add package Xpandables.Generators --version 11.0.0
NuGet\Install-Package Xpandables.Generators -Version 11.0.0
<PackageReference Include="Xpandables.Generators" Version="11.0.0" />
<PackageVersion Include="Xpandables.Generators" Version="11.0.0" />
<PackageReference Include="Xpandables.Generators" />
paket add Xpandables.Generators --version 11.0.0
#r "nuget: Xpandables.Generators, 11.0.0"
#:package Xpandables.Generators@11.0.0
#addin nuget:?package=Xpandables.Generators&version=11.0.0
#tool nuget:?package=Xpandables.Generators&version=11.0.0
π¦ System.Generators (Xpandables.Generators)
Roslyn incremental source generators, analyzers and code fixes for the Xpandables libraries β handler, event consumer, validator, service and repository registrations, data record metadata, JSON converters and REST request completion, all written at compile time so that nothing is discovered by reflection and every library runs under trimming and Native AOT.
Overview β’ Getting Started β’ Diagnostics
π Overview
Xpandables.Generators ships every Roslyn incremental source generator of the Xpandables libraries in one package. Each generator reacts only to the contracts of its own library, matched by metadata name: in a project that does not reference that library it generates nothing and reports nothing, so referencing the package costs nothing for the libraries a project does not use. No generator references the libraries it serves.
| Component | Library served | Triggered by | Emits |
|---|---|---|---|
HandlerSourceGenerator |
Xpandables.Handlers | classes and records implementing a handler, behavior or exception-handler interface | AddX{Assembly}Handlers() |
EventConsumerRegistrationGenerator |
Xpandables.Events | classes and records implementing IEventConsumer<TEvent> |
AddX{Assembly}EventConsumers() |
ValidatorGenerator |
Xpandables.Validations | IRequiresValidation types with DataAnnotations rules, IValidator<T> classes |
one validator per validated type, AddX{Assembly}Validators() |
ServiceRegistrationGenerator |
Xpandables.Net, Xpandables.AspNetCore.Net | IAddService, IUseService, IMinimalEndpointRoute, [CacheType], IEvent types |
AddXServicesGenerated, UseXServicesGenerated(Async), AddXMinimalEndpointRoutesGenerated, AddX{Assembly}CacheTypes() |
OptionalJsonConverterGenerator |
Xpandables.Net | every closed Optional<T> named in source |
a module initializer registering the JSON converters |
RestRequestGenerator |
Xpandables.Rests | classes, structs and records implementing IRestRequest |
a partial declaration implementing IRestAttributeBuilder and the stream deserializers |
RestRequestPartialAnalyzer + "Make partial" code fix |
Xpandables.Rests | a request that must be completed but is not partial |
XRR005, fixed by adding partial |
DataRecordGenerator |
Xpandables.Data | [DataRecord] on a type or [assembly: DataRecord(typeof(T))] |
DataRecordMetadata<T> per record and a module initializer |
DataValueGenerator |
Xpandables.Data | [DataValue] on a type or [assembly: DataValue(typeof(T))] |
a module initializer registering the value objects |
DataQueryArgsGenerator |
Xpandables.Data | [DataQueryArgs] on a partial type |
IDataQueryArgs.ReadSlots() and the slot registration |
DataRepositoryRegistrationGenerator |
Xpandables.Data | sealed classes implementing a repository interface | AddXDataRepositoriesGenerated(lifetime) |
CompiledQueryOverloadGenerator |
Xpandables.Data (internal) | the internal [GenerateCompiledQueryOverloads] and [GenerateCompiledUpdateOverloads] markers |
the compiled-query and compiled-update execution overloads |
DataQueryBuilderResultAnalyzer + "Assign the result" code fix |
Xpandables.Data | a DataQueryBuilder<T> returned by any call and dropped |
XDQ004, fixed by assigning the result |
CompiledDataFactoryAnalyzer |
Xpandables.Data | the factory of a DataQuery.Compile or DataUpdater.Compile call |
XDQ005, XDQ006 |
PagedOperatorGenerator |
Xpandables.AsyncPaged (internal) | the internal [OwnsPagedOperators] attribute |
the paged LINQ overloads |
π Getting Started
Xpandables.Net, Xpandables.AspNetCore.Net, Xpandables.Handlers, Xpandables.Events, Xpandables.Validations, Xpandables.Data and Xpandables.Rests depend on this package, so their consumers get the generators without referencing it. A project that references none of them adds it explicitly:
dotnet add package Xpandables.Generators
<ItemGroup>
<PackageReference Include="Xpandables.Generators" Version="11.0.0" PrivateAssets="all" />
</ItemGroup>
The generators are built against Roslyn 5.9, the compiler of the .NET SDK 10.0.400 and later. An older SDK cannot load
them (warning CS8032) and nothing is generated; the libraries target .NET 11, so a solution using them builds with the .NET 11 SDK;
a global.json keeps every machine on it:
{
"sdk": {
"version": "10.0.401",
"rollForward": "latestFeature"
}
}
The generators run at compile time; there is nothing to configure. The generated files are visible in the IDE under
Dependencies βΊ Analyzers βΊ Xpandables.Generators and, with <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>,
under obj/.
Rules shared by the generators
- No reflection, no scanning. Every registration names closed types in generated code. A type the generated code cannot reference is reported (each generator has its own id) and is not registered; nothing falls back to a run-time discovery.
- Assembly-named registrations. The handler, event consumer and validator registrations are
publicand carry the assembly name, so several assemblies using the generators coexist in one application.{Assembly}is the assembly name as an identifier: dots dropped with each segment capitalized, other non-identifier characters removed,_before a leading digit (Shop.OrdersβShopOrders,My.App-2βMyApp2). - Name collisions (
XGN001). Two assembly names that map to one identifier (My.App,MyApp) generate the same class. When a referenced assembly already declares it, the generator reportsXGN001(no source location): calls are ambiguous (CS0121) where both are visible; rename one of the assemblies. It is not reported through an extern alias, nor in a project that references two such assemblies without generating the class itself. [Obsolete]and[Experimental]. A handler, behavior, request, event consumer, event, validator, validated type, cache type, data value, data record (and its column, base and constructor parameter types), data repository orOptional<T>value type marked[Obsolete](warning form) or[Experimental]β on itself, a containing type, a type argument, its module or its assembly β is registered, and the generated file disables exactly the ids it raises. The error form of[Obsolete](CS0619) cannot be suppressed: such a type is reported and not registered (XHG001,XEC001,XVA001,XDV003,XDR003,XOJ001; a cache type or a data repository is skipped). AnIAddService,IUseServiceorIMinimalEndpointRoutemarked[Obsolete]in either form is not registered (XSR001,XSR002); an[Experimental]one is.- Required members. A
new()constraint or anew T()is satisfied only when the type has no required members, or its parameterless constructor is[SetsRequiredMembers](the[DataQueryArgs]placeholder sets them instead). - Members. A data record or data value constructor, factory or property
[Obsolete]as an error is not used (a record falls back to another constructor; a column property reportsXDR003, a column whose data value cannot be usedXDR002, the value itselfXDV003); the ids of the others are disabled in the generated file. - Generated text. Every generated file starts with
// <auto-generated/>, so analyzers and code-style rules skip it.
π Handler Registration (Xpandables.Handlers)
HandlerSourceGenerator writes, for each assembly that declares request handlers or pipeline behaviors, one file
{Assembly}HandlerRegistrations.g.cs:
using System.Handlers;
using System.Handlers.Generated;
using Microsoft.Extensions.DependencyInjection;
// The method generated for the assembly "Shop.Orders":
builder.Services.AddXMediator();
builder.Services.AddXShopOrdersHandlers();
Given (members elided):
public sealed class GetOrderHandler : IRequestHandler<GetOrderQuery, Order> { }
public sealed class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : class, IRequest<TResponse> { }
the generator produces (namespaces shortened):
namespace System.Handlers.Generated
{
public static class ShopOrdersHandlerRegistrations
{
public static IServiceCollection AddXShopOrdersHandlers(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);
HandlerServiceCollectionExtensions.AddXRequestHandler<GetOrderQuery, Order, GetOrderHandler>(services);
HandlerServiceCollectionExtensions.AddXPipelineBehavior<GetOrderQuery, Order, LoggingBehavior<GetOrderQuery, Order>>(services);
// Authorization: every request carrying the marker
HandlerServiceCollectionExtensions.AddXAuthorizationBehavior<GetOrderQuery, Order>(services);
return services;
}
}
}
- Handlers, behaviors, pre- and post-behaviors and exception handlers of every request shape (void, response, stream,
paged stream) are registered with closed types through the
HandlerServiceCollectionExtensionsmethods of their shape (AddXPipelineBehavior,AddXStreamPipelineBehavior,AddXStreamPagedPipelineBehavior, β¦). Classes and records are both discovered; a pre-behavior is registered once per request. - A generic behavior whose type parameters are those of its pipeline interface is closed over every request of the
assembly whose shape and type arguments satisfy its constraints.
struct,notnulland non-nullableclassconstraints skip nullable type arguments; anew()constraint follows the required-members rule above. - The built-in behaviors are registered per request by its markers:
AuthorizationforIAuthorizedRequest;Cachingfor void and responseICacheableRequest; in an assembly that references Xpandables.AspNetCore.Net, validation forIRequiresValidation(every shape), unit of work for void and responseIRequiresDataUnitOfWork, and idempotency for those also implementingIIdempotentRequest, withAddXIdempotencyKey<T>when the key is settable (an accessibleset, or an accessibleiniton a record). The exception behavior is registered with each exception handler. Such an assembly (the web host) also closes the validation, unit-of-work and idempotency behaviors, and the key setters, for the public marked requests of the referenced libraries that reference Xpandables.Handlers but not Xpandables.AspNetCore.Net: call the host'sAddX{Host}Handlers(). An application without Xpandables.AspNetCore.Net (a worker host) reports those of the libraries that generate a registration instead (XHG005, once per request and marker, naming the library); a contracts-only library, or one whose handlers are registered by hand, generates none and is not reported. - Behaviors and exception handlers are registered even when the request's handler lives in another assembly (
XHG003). - The registrations go through
TryAdd/TryAddEnumerable: calling the method again registers nothing more, and a handler already registered for a request keeps its registration. - Nothing is generated for an assembly with nothing to register, nor without the
System.Handlerscontracts, nor in Xpandables.Handlers itself.
| Diagnostic | Severity | Meaning |
|---|---|---|
XHG001 |
Warning | A handler or behavior cannot be referenced by the generated code (private or protected nested, file-local, nested in a generic type, [Obsolete] as an error, or its request or response type cannot be referenced) and is not registered; the message says which. |
XHG002 |
Warning | A generic behavior matches no request of the assembly (shape and constraints) and is not registered. |
XHG003 |
Info | A request has behaviors but no handler in the assembly; the behaviors are registered here, the handler must be registered by the assembly that declares it. |
XHG004 |
Error | A request carries a marker no built-in behavior serves (IRequiresDataUnitOfWork or IIdempotentRequest on a stream, paged or value-type request, ICacheableRequest on a stream or paged request, IRequiresValidation on a value-type request); it is not applied. |
XHG005 |
Error | An application without Xpandables.AspNetCore.Net handles a request carrying a marker whose behavior is in it (IRequiresValidation, IRequiresDataUnitOfWork or IIdempotentRequest), or references a library that generates a handler registration and declares such a public request; reported once per request and marker, naming the assembly that declares the request. A contracts-only library is not reported. |
XHG006 |
Error | Two handlers of one request in the assembly; the second is not registered. |
XHG007 |
Error | A request implements IIdempotentRequest without IRequiresDataUnitOfWork: its response must be stored in the handler's transaction. |
π¨ Event Consumer Registration (Xpandables.Events)
EventConsumerRegistrationGenerator writes, for each assembly that declares event consumers,
{Assembly}EventConsumerRegistrations.AddX{Assembly}EventConsumers(this IServiceCollection) in the namespace
System.Events.Generated:
using System.Events.Generated;
builder.Services.AddXShopOrdersEventConsumers();
- Every non-abstract class or record class implementing
IEventConsumer<TEvent>is registered once per implemented interface: throughAddXIntegrationEventConsumer<TEvent, TConsumer>()whenTEventis anIIntegrationEvent(wrapped in the inbox behavior), else throughAddXEventConsumer<TEvent, TConsumer>(services, null). - An open consumer
C<TEvent> : IEventConsumer<TEvent>is closed over every concrete, accessible, non-generic event class of the assembly that satisfies its constraints (base types, interfaces,new(); astructconstraint matches nothing). Any other generic shape is reported (XEC002). - Consumers need not be sealed. Nothing is generated without the
System.Eventscontracts, nor in the assembly that declares them, nor for an assembly with no consumer.
| Diagnostic | Severity | Meaning |
|---|---|---|
XEC001 |
Warning | A consumer cannot be referenced by the generated registration (private or protected nested, file-local, nested in a generic type, [Obsolete] as an error, or its event type is [Obsolete] as an error or not accessible to generated code) and is not registered; the message says which. |
XEC002 |
Warning | An open-generic consumer is not registered: no event of the assembly satisfies its constraints, or its type parameters are not just the event. |
π Saga Registration (Xpandables.Sagas)
SagaRegistrationGenerator writes, for each assembly that declares sagas,
{Assembly}SagaRegistrations.AddX{Assembly}Sagas(this IServiceCollection) in the namespace System.Sagas.Generated:
using System.Sagas.Generated;
builder.Services.AddXSagas().AddXShopOrdersSagas();
- Every accessible, non-abstract, non-generic class deriving from
Saga<TData>with a public parameterless constructor is registered withAddXSaga<TSaga>();[ExcludeFromRegistration]leaves one out (a previous version registered by hand, a test saga). - Nothing is generated without Xpandables.Sagas, nor in the assembly that declares it, nor for an assembly with no saga.
| Diagnostic | Severity | Meaning |
|---|---|---|
XSG001 |
Warning | A saga is not registered: it is generic, inaccessible to generated code, [Obsolete] as an error, or has no public parameterless constructor; the message says which. |
βοΈ Validators (Xpandables.Validations)
ValidatorGenerator runs in every project that references Xpandables.Validations:
- For every non-abstract class or record class that implements
IRequiresValidationand declares DataAnnotations rules (validation attributes on its public properties or on the type, orIValidatableObject), it writes aninternal sealedvalidator inSystem.ComponentModel.DataAnnotations.Generatedwith the semantics ofValidator.TryValidateObject(β¦, validateAllProperties: true): the propertiesTypeDescriptorsees (most derived type first, declaration order, each name once);[Required]first for each property, then its other attributes; the type's attributes only when no property failed;IValidatableObject.Validateonly when nothing failed. Display names come from[Display]. The attributes are rebuilt as code from the compilation (constructor and named arguments) and checked throughGeneratedValidation; nothing is read by reflection. A generated validator'sOrderisint.MinValue, so the attribute rules run before the type's other validators. AddX{Assembly}Validators()(class{Assembly}ValidatorRegistrations, namespaceMicrosoft.Extensions.DependencyInjection) registers every validator class of the assembly (closedIValidator<T>implementations, composite validators excepted) and every generated validator throughAddXValidator<T, TValidator>(). It is idempotent (TryAddEnumerable), emitted when there is something to register, and always in an executable. Each project also records, as[assembly: AssemblyMetadata]entries, the types its validators validate (internal validators included) and the types it leaves without rule or validator: the application reads them to checkXVA004across the projects it references, and to tell whether it validates at all. A validator marked[ReplacesAttributeValidation](inherited by derived validators) replaces the generated attribute validator of the type it validates: in the same assembly that one is not registered; in a project that references the type's project, the validator is registered withAddXReplacingValidator<T, TValidator>(), which removes the attribute validator whicheverAddX{Assembly}Validators()is called first.
builder.Services.AddXShopOrdersValidators();
| Diagnostic | Severity | Meaning |
|---|---|---|
XVA001 |
Warning | A validator class or a validated type with rules is not accessible from the generated code (private nested, file-local, [Obsolete] as an error), or a validator's validated type cannot be referenced, or a validator has no public constructor; it is not registered. |
XVA002 |
Warning | A validator class or a validated type with rules is generic; register its closed forms with AddXValidator<T, TValidator>(). |
XVA003 |
Error | An attribute cannot be rebuilt by the generated validator (inaccessible constructor or type, or an argument that cannot be written as C#); the type is not validated by attributes. Not reported when the type's validator replaces attribute validation ([ReplacesAttributeValidation]). |
XVA004 |
Error | Reported by an application (an executable project) that validates: one that declares a validator, references a project that declares one (internal validators included), or references Xpandables.AspNetCore.Net, whose endpoint filters validate requests. A client that only sends the shared requests (serialized, never validated) is not checked, nor is a library: its validator may live in a project that references it. The MSBuild property <XpandablesValidationCheck>true</XpandablesValidationCheck> forces the check (a server with no validator yet, or any project), false turns it off. Checked: a concrete, non-generic, accessible class implementing IRequiresValidation, of the application or of a referenced project, has no usable rule (attributes on public readable instance properties or on the type, IValidatableObject) and no validator in the application nor in a referenced project (one marked [ExcludeFromRegistration] counts); an attribute on a positional record parameter needs [property: β¦]. Each project records, as [assembly: AssemblyMetadata] entries, the types its validators validate and the types it leaves without rule or validator; the application reads them and reports an imported type at no source location, naming the type and its assembly, one diagnostic per type, ordered by assembly then type. Each validation of such a type throws InvalidOperationException. Mark the type [ValidatorResolvedAtRuntime] when a custom IValidatorProvider supplies its validator; suppress it when the validator is registered by hand in a form the generator cannot relate to the type (an open generic validator closed with AddXValidator, a validator of a base type or interface), project-wide with <NoWarn>$(NoWarn);XVA004</NoWarn> in the application or dotnet_diagnostic.XVA004.severity = none in .editorconfig. |
π§© Service Registration (Xpandables.Net)
ServiceRegistrationGenerator discovers service modules, endpoint routes and cache types at compile time and writes
their registration, so they register under trimming and Native AOT:
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddXServicesGenerated(builder.Configuration)
.AddXMinimalEndpointRoutesGenerated()
.AddXShopApiCacheTypes() // this project's cache types and events
.AddXShopOrdersCacheTypes(); // and each referenced project's: internal types included, merged
var app = builder.Build();
await app.UseXServicesGeneratedAsync();
Generated methods
A file is emitted when its contract type is referenced by the project and there is something to register β and always in an executable, so that the documented call compiles before the first service exists.
| Method | Class (namespace) | Contract | Behaviour |
|---|---|---|---|
AddXServicesGenerated(this IServiceCollection, IConfiguration) and AddXServicesGenerated(this IServiceCollection) |
GeneratedServiceRegistrationExtensions (Microsoft.Extensions.DependencyInjection) |
System.Composition.IAddService |
Calls AddServices(services, configuration) / AddServices(services) on a new instance of every discovered IAddService |
UseXServicesGenerated(this WebApplication) and UseXServicesGeneratedAsync(this WebApplication, CancellationToken) |
GeneratedApplicationServiceExtensions (Microsoft.AspNetCore.Builder) |
Microsoft.AspNetCore.Builder.IUseService (Xpandables.AspNetCore.Net) |
Calls UseServices / awaits UseServicesAsync on a new instance of every discovered IUseService, in ascending Order; equal orders keep the full-name order |
AddXMinimalEndpointRoutesGenerated(this IServiceCollection) |
GeneratedEndpointRouteExtensions (Microsoft.Extensions.DependencyInjection) |
Microsoft.AspNetCore.Routing.IMinimalEndpointRoute (Xpandables.AspNetCore.Net) |
Registers every discovered route once (TryAddEnumerable) as a transient IMinimalEndpointRoute, built by the container (constructor injection); UseXMinimalEndpointRoutes maps them |
AddX{Assembly}CacheTypes(this IServiceCollection) |
{Assembly}CacheTypeRegistrations, public (Microsoft.Extensions.DependencyInjection) |
System.CacheTypeAttribute, System.Events.IEvent |
Adds the project's own cache types and events, internal ones included, with AddXCacheTypes (Xpandables.Net) and AddXEventTypes (Xpandables.Events): the singleton ICacheTypeResolver and EventTypeRegistry merge the contributions of every project that calls its own. Calling it twice adds nothing |
The generated classes are internal, except {Assembly}CacheTypeRegistrations, which is public and named after its
assembly so that each project can call another's: every assembly running the generator gets its own copy, and the copies of
referenced assemblies are invisible to it. With InternalsVisibleTo between two assemblies that both run the
generator, the second sees both copies and gets type-conflict warnings (CS0436) and ambiguous calls (CS0121): run the
generator in only one of them, or do not link them with InternalsVisibleTo.
What is discovered
- Types declared in the project, and the public types of referenced assemblies that are named
Xpandables.*or reference anXpandables.*assembly (plugins). Only direct references are inspected: an assembly whose types implement a contract only through a base class declared in an intermediate assembly, without itself referencing anXpandables.*assembly, is not scanned. An assembly bound only through an extern alias is skipped. - Only concrete, non-generic types the project can access: abstract, static and open generic types, private nested
types, file-local types, ref structs and types not accessible from the consuming project (internal ones unless
InternalsVisibleTo) are ignored. IAddServiceandIUseServiceimplementations need an accessible, non-[Obsolete]parameterless constructor (marked[SetsRequiredMembers]when the type has required members).IMinimalEndpointRouteimplementations are classes with a public constructor, built by the container; they need not be sealed. A concrete base route and its subclass are both mapped (the same routes twice): make a base route abstract. The public routes of referenced libraries are mapped too.- Cache types are the
[CacheType]types and the concreteSystem.Events.IEventimplementations declared in the project,internalones included (each project registers its own), each named by its own rule:- non-event cache types: the
[CacheType("name")]argument, else the simple type name; - events: the
[EventName("name")]argument, else the simple type name;[CacheType]'s argument is ignored.
- non-event cache types: the
[CacheType("orders.summary")]
public sealed record OrderSummary(string Id, decimal Total); // "orders.summary"
[CacheType]
public sealed record CustomerView(string Id); // "CustomerView"
[EventName("Ordering.OrderPlaced.v1")]
public sealed record OrderPlaced : EventBase; // "Ordering.OrderPlaced.v1"
When two cache types share a name, the first in ordinal full-name order is kept and XCT001 fails the build. The check
spans projects: each project records its cache-type names, event names and aliases as [assembly: AssemblyMetadata]
entries (internal types included); a project reports a clash between its own names and a referenced project's
(XCT001, XCT003), and an application also reports clashes between two projects it references. At run time the
resolver and the registry refuse one name claimed by two types.
Events also get an EventTypeRegistry (added to by the same AddX{Assembly}CacheTypes()): each event's name, its [EventName(β¦, Version = n)] version (1 by default) and its [EventNameAlias] former names.
| Diagnostic | Severity | Meaning |
|---|---|---|
XSR001 |
Warning | An IAddService or IUseService implementation cannot be instantiated by the generated code and is not registered: no accessible, non-[Obsolete] parameterless constructor (marked [SetsRequiredMembers] when the type has required members), the type or a containing type is [Obsolete], or it is nested in a generic type (reported where it is declared). The message says which. For a type of a referenced assembly the warning has no source location. |
XSR002 |
Warning | An IMinimalEndpointRoute the project declares cannot be registered (not accessible, nested in a generic type, a struct, [Obsolete], or no public constructor that is not [Obsolete]); the message says which. |
XCT001 |
Error | Two cache types share a name. The message names both types and the name; it is reported once per pair, with no source location. |
XCT002 |
Error | A [CacheType("...")] name (non-event types), or an [EventName("...")] name or an [EventNameAlias("...")] (events), is empty or whitespace; the type is not registered. An empty [CacheType] argument on an event is ignored, not reported. For a type of a referenced assembly the diagnostic has no source location. |
XCT003 |
Error | An [EventNameAlias] repeats the name or an alias of another event. The message names both types and the name; the second claim is left out of the registry. |
XCT004 |
Error | An [EventName] declares a Version below 1; the type is not registered. |
π Optional JSON Converters (Xpandables.Net)
OptionalJsonConverterGenerator finds every closed System.Optionals.Optional<T> the project's source names (in a
type, a declaration, typeof(Optional<X>), β¦) and writes a module initializer, in System.Optionals.Generated, that
calls
OptionalJsonConverters.Register<T>() for each distinct T. System.Text.Json then serializes those types without
reflection.
- The value types
OptionalJsonConverterFactoryhandles itself are skipped:int,long,short,float,double,decimal,ushort,byte,bool,DateTime,DateTimeOffset,Guid. - An
Optional<T>whoseTcontains a type parameter (Optional<TValue>in generic code) is not registered: close it where it is used. - The registration file is produced at build time only (it is not shown in the IDE);
XOJ001is reported as you type. - Nothing is generated without
OptionalJsonConvertersin the compilation.
| Diagnostic | Severity | Meaning |
|---|---|---|
XOJ001 |
Warning | Optional<T> gets no generated converter: generated code cannot name T or one of its type arguments (an internal type of another assembly, a private nested or file-local type), or T is [Obsolete] as an error; the message says which. |
π REST Requests (Xpandables.Rests)
RestRequestGenerator completes each request (a class, struct or record implementing IRestRequest) in a generated
partial declaration, so the Xpandables.Rests runtime reads nothing by reflection:
IRestAttributeBuilder.Buildreturns the request's[Restβ¦]attribute rebuilt as code, held in one immutable static instance per request type (no allocation per send). The builder is implemented where the attribute is declared; requests deriving from it inherit it. A request declaring its own attribute re-implements it (the most derived attribute wins). A request whose attribute comes from a base compiled without the generator is completed with that attribute when the attribute isInherited.- Stream deserializers. A request implementing
IRestRequestStream<T>getsIRestStreamDeserializer<T>, one implementingIRestRequestStreamPaged<T>getsIRestStreamPagedDeserializer<T>; their default interface members do the work. The interface is added where the stream contract is introduced, unless the request already implements it. - A hand-written
Build(or an override of a base's virtualBuild) or deserializer is never replaced. - The request and every type containing it must be
partial. A request that is not is left alone, andRestRequestPartialAnalyzerreportsXRR005as you type; the "Make partial" code fix (Xpandables.Generators.CodeFixes, in this package) addspartialto the request and to every containing type that lacks it, Fix All included.RunAnalyzers=falseskips the analyzer while the generator still runs. - Obsolete and experimental members used by the attribute are suppressed in the generated file: the attribute was applied knowingly.
- Nothing is generated without the
System.Restscontracts, nor in Xpandables.Rests itself.
// Completed with IRestAttributeBuilder: Build() returns this [RestGet] attribute, rebuilt as code.
[RestGet("/api/users/{userId}", Location = RestSettings.Location.Path)]
public sealed partial record GetUserRequest(Guid UserId)
: IRestRequestResult<User>, IRestPathString
{
public IDictionary<string, string> GetPathString() =>
new Dictionary<string, string> { ["userId"] = UserId.ToString() };
}
| Diagnostic | Severity | Meaning |
|---|---|---|
XRR001 |
Error | The [Restβ¦] attribute cannot be rebuilt by generated code (inaccessible type, constructor or argument); make it accessible, or implement IRestAttributeBuilder. |
XRR002 |
Error | The request is file-local: a generated partial declaration cannot complete it; declare it internal or public. |
XRR003 |
Error | The element type of a stream request is not accessible from generated code; implement the deserializer interface on the request, or make the type accessible. |
XRR004 |
Error | The request has several [Restβ¦] attributes; keep one, or implement IRestAttributeBuilder. |
XRR005 |
Error | The request, or a type containing it, is not partial (reported by the analyzer; code fix "Make partial"). |
ποΈ Data (Xpandables.Data)
Xpandables.Data reads the shape of its types only from the code these generators write. See the Xpandables.Data README, sections Data Records, Data Values and Compiled Queries, for how the library uses it.
Data records β DataRecordGenerator
For each type marked [DataRecord], or listed with [assembly: DataRecord(typeof(T))], an internal sealed class
deriving from DataRecordMetadata<T> in System.Data.Generated, and one module initializer per assembly registering them in
DataRecords. A type declared twice is emitted once.
- Table:
[Table("name", Schema = "...")], else the type name. - Columns: the public instance properties with a public getter, inherited ones included (most derived first, an
overriding or hiding property taken once), except
[NotMapped]. The column name comes from[Column("name")](TypeNameis kept as the SQL type), else the property name. - Column types:
bool,char, the integer and floating-point types,decimal,string,DateTime,DateTimeOffset,DateOnly,TimeOnly,TimeSpan,Guid,Int128,UInt128,Half,nint,nuint,object,byte[], enums, theirNullable<T>, and data values (stored as their primitive). - Keys: the
[Key]properties; without any, the property namedId(case-insensitive). - Generated columns:
[DatabaseGenerated(Identity)]and[DatabaseGenerated(Computed)]are refreshed after writes;[Timestamp]is a row-version concurrency token;[ConcurrencyCheck]on a settableintorlongis a version number the repository compares and increments ([Timestamp]wins when a property carries both). - Nullability:
[Required]is never null; a value type is nullable when it isNullable<T>; a reference type unless annotated non-null (oblivious and[MaybeNull]count as nullable). - Construction: the public constructors (parameters matched to columns by name, case-insensitive) and the
parameterless one.
initand inaccessible setters, and constructors that leave required members unset, are reached through[UnsafeAccessor], never reflection.
| Diagnostic | Severity | Meaning |
|---|---|---|
XDR001 |
Error | The record has no public constructor the row reader can call. |
XDR002 |
Error | A property's type is not a column type; mark it [NotMapped] or use a scalar type. |
XDR003 |
Error | The type cannot be a data record: not a class or struct, generic, abstract or static, inaccessible to generated code, [Obsolete] as an error (or the type of one of its columns is, or a column property, its getter, or the base type that declares it β mark it [NotMapped]), or a struct with required members and no [SetsRequiredMembers] constructor. |
XDR004 |
Error | A [ConcurrencyCheck] version number is not int/long, has no set accessor (init does not count), or is on a struct record. |
XDR005 |
Warning | A database-generated column has no setter: it is not refreshed after writes. |
XDR006 |
Error | Two properties map to the same column (case-insensitive). |
Data values β DataValueGenerator
For each value object marked [DataValue], or listed with [assembly: DataValue(typeof(T))], a registration in
DataValues (one module initializer per assembly) of how it unwraps to its primitive and wraps back.
The primitive is the parameter of the single public one-parameter constructor, else of the single public static
From/Create method returning the type; the value is the public property of that type, preferring the one named
like the parameter. A data value declared by a referenced assembly's [assembly: DataValue] is registered again by the
assembly whose records use it.
| Diagnostic | Severity | Meaning |
|---|---|---|
XDV001 |
Error | No single scalar value: the type needs a public constructor (or static From/Create) with one parameter and a public property of that type. |
XDV002 |
Error | The primitive is not a column type with one meaning in every database (object, nint and nuint are excluded), or is itself a data value. |
XDV003 |
Error | The type cannot be a data value: not a class or struct, generic, abstract or static, inaccessible to generated code, or [Obsolete] as an error (the type, its constructor or From/Create factory, its value property, or its primitive type). |
Compiled-query arguments β DataQueryArgsGenerator
For each partial type marked [DataQueryArgs], the generator implements IDataQueryArgs (unless the type already
does): ReadSlots() returns the public readable instance properties the type itself declares (inherited ones are not
slots), in declaration order (unless the type declares ReadSlots()), and a module initializer calls DataQueryArgs.Register<T> with the slot names, their nullability and a
placeholder factory. The placeholder is built through the accessible constructor with the most parameters, each int
slot receiving its paging marker through the matching parameter (by name, case-insensitive) or its setter, every other
parameter default; the required members that constructor does not set (no [SetsRequiredMembers]) are set in the
object initializer (a marker for an int slot, default otherwise). A member whose name is a keyword (@class) is
written escaped. This is how
Xpandables.Data learns the shape of an argument type: it never reflects on one.
[DataQueryArgs]
public sealed partial record ProductFilter(decimal MinPrice, int CategoryId, int PageIndex, int PageSize);
| Diagnostic | Severity | Meaning |
|---|---|---|
XDQ001 |
Error | The [DataQueryArgs] type is not partial. |
XDQ002 |
Error | Unsupported shape: generic, abstract or static, a containing type that is not partial, or no accessible constructor. |
XDQ003 |
Error | An int property is neither a constructor parameter nor settable: passed to Skip/Take/Top/Page it would read 0. |
XDQ004 |
Error | The DataQueryBuilder<T> returned by a call is discarded (DataQueryBuilderResultAnalyzer): the builder is immutable, so query.Where(...); changes nothing. Any call returning the builder is reported β a builder method, an extension (query.Paged(2)), a helper (Filters.OwnedBy(query, "me")) β including through ?. and an awaited or Task/ValueTask-returning helper. Assign the result (query = query.Where(...)); an explicit discard _ = β¦ and generated code are not reported. The "Assign the result" code fix (Xpandables.Generators.CodeFixes, Fix All in document, project or solution) rewrites the statement into query = query.Where(...); it is offered when the receiver at the root of the chain is an assignable local, field, settable property or ref/out parameter of the builder's type; not offered for a by-value parameter (return the builder instead), a helper call, an await, a value-type receiver. A stored task of the builder dropped by await pending; is reported too: assign it (query = await pending;). |
XDQ005 |
Error | The factory of a DataQuery.Compile or DataUpdater.Compile call evaluates one of its arguments (CompiledDataFactoryAnalyzer): a constant SetProperty(e => e.Name, args.Value), an argument passed to a method the factory calls (Updater(args.Value)), a condition (if (args.Value > 0)), or a local assigned from the argument and captured by an expression (var min = args.Value; Where(e => e.Price > min)). The factory runs once, so every execution would use the placeholder (default, or a paging marker for an int). Read the argument directly inside the expression β Where(e => e.Price > args.Value), SetProperty(e => e.Name, e => args.Value) β or pass the argument object itself to the method. An int argument passed to Skip/Take/Top/Page, directly or through a local, is how it pages and is not reported. |
XDQ006 |
Warning | The factory of a DataQuery.Compile or DataUpdater.Compile call reads a value that changes between calls β DateTime.Now/UtcNow/Today, DateTimeOffset.Now/UtcNow, Guid.NewGuid()/CreateVersion7(), TimeProvider.GetUtcNow()/GetLocalNow()/GetTimestamp() (overrides included), Environment.TickCount, Stopwatch.GetTimestamp(), Random.Nextβ¦ β even inside an expression (CompiledDataFactoryAnalyzer): the compiled statement keeps the first value. Pass it as an argument. A member of your own (_clock.Now) is not known and not reported. |
Repositories β DataRepositoryRegistrationGenerator
For an assembly that declares repositories, AddXDataRepositoriesGenerated(this IServiceCollection, ServiceLifetime lifetime = ServiceLifetime.Scoped)
(internal, class GeneratedDataRepositoryRegistrationExtensions, namespace Microsoft.Extensions.DependencyInjection).
Each sealed, concrete, non-generic, accessible class implementing IDataRepository is registered under each of its
interfaces that extends IDataRepository and that generated code can reference, with TryAdd: an interface already
registered keeps its registration. An inaccessible interface, or one [Obsolete] as an error, is skipped, and a class
left with none (or [Obsolete] as an error itself) is not registered; nothing is reported.
builder.Services.AddXDataRepositoriesGenerated(ServiceLifetime.Scoped);
Compiled-query overloads β CompiledQueryOverloadGenerator
Writes, into the class carrying the internal [GenerateCompiledQueryOverloads] marker, the QueryAsync,
QueryFirstOrDefaultAsync, QuerySingleOrDefaultAsync and CountAsync extension methods on IDataRepository<TData>
for every CompiledDataQuery arity from 0 to 8, and, into the class carrying [GenerateCompiledUpdateOverloads], the
UpdateAsync extension methods for every CompiledDataUpdate arity from 0 to 8. Only Xpandables.Data carries the
markers, so its consumers never get the overloads twice.
π§ Paged Operators (Xpandables.AsyncPaged)
PagedOperatorGenerator writes the paged LINQ overloads of Xpandables.AsyncPaged: for every deferred operator of
System.Linq.AsyncEnumerable it emits the same signature with an IAsyncPagedEnumerable<T> receiver and return type,
whose body calls the BCL operator and wraps the result, keeping the source's pagination. A hand-written overload with
the same CLR shape always wins: the generator skips it. Which class receives an operator is set by
[OwnsPagedOperators("Name", β¦)] on the owning partial class (an internal [Conditional] attribute, absent from the
compiled assembly); an operator no attribute names goes to PagedOperatorExtensions.
It is gated on that attribute in the compilation's own source: it runs when System.AsyncPaged builds and generates nothing β and reports nothing β in any other project, including those that reference Xpandables.AsyncPaged. The public-API snapshot of System.AsyncPaged pins the generated surface.
| Diagnostic | Severity | Meaning (reported only while System.AsyncPaged builds) |
|---|---|---|
XPG001 |
Error | A BCL operator returning a sequence has no paged overload and cannot be generated: declare it by hand in System.AsyncPaged/System.Linq. |
XPG002 |
Error | A class owning paged operators is not partial. |
XPG003 |
Error | A required type (AsyncEnumerable, IAsyncEnumerable<T>, IOrderedAsyncEnumerable<T>, the paged interfaces, OwnsPagedOperatorsAttribute) was not found. |
XPG004 |
Error | An operator name is claimed by two owning classes. |
π©Ί Diagnostics Reference
All diagnostics are in the Usage category and enabled by default.
| ID | Severity | Title | Reported by |
|---|---|---|---|
XGN001 |
Warning | Generated type collides with a referenced assembly's | Handler, event consumer and validator generators |
XHG001 |
Warning | Handler type cannot be referenced by generated code | HandlerSourceGenerator |
XHG002 |
Warning | Open-generic behavior matches no request | HandlerSourceGenerator |
XHG003 |
Info | Request has no handler in this assembly | HandlerSourceGenerator |
XHG004 |
Error | Request marker that no behavior serves | HandlerSourceGenerator |
XHG005 |
Error | Request marker whose behavior is not referenced | HandlerSourceGenerator |
XHG006 |
Error | Request has two handlers | HandlerSourceGenerator |
XHG007 |
Error | Idempotent request without a unit of work | HandlerSourceGenerator |
XEC001 |
Warning | Event consumer cannot be referenced by generated code | EventConsumerRegistrationGenerator |
XEC002 |
Warning | Open-generic event consumer matches no event | EventConsumerRegistrationGenerator |
XSG001 |
Warning | Saga cannot be registered by generated code | SagaRegistrationGenerator |
XVA001 |
Warning | Validator or validated type not accessible from generated code | ValidatorGenerator |
XVA002 |
Warning | Generic validator or validated type | ValidatorGenerator |
XVA003 |
Error | Validation attribute cannot be rebuilt by generated code | ValidatorGenerator |
XVA004 |
Error | Validated type without validator | ValidatorGenerator |
XSR001 |
Warning | Service type cannot be registered | ServiceRegistrationGenerator |
XSR002 |
Warning | Endpoint route cannot be registered | ServiceRegistrationGenerator |
XCT001 |
Error | Duplicate cache type name | ServiceRegistrationGenerator |
XCT002 |
Error | Cache type name, event name or alias is empty | ServiceRegistrationGenerator |
XCT003 |
Error | Duplicate event name or alias | ServiceRegistrationGenerator |
XCT004 |
Error | Event version is not positive | ServiceRegistrationGenerator |
XOJ001 |
Warning | Optional<T> converter cannot be generated |
OptionalJsonConverterGenerator |
XRR001 |
Error | REST attribute cannot be rebuilt | RestRequestGenerator |
XRR002 |
Error | REST request is file-local | RestRequestGenerator |
XRR003 |
Error | Stream element type not accessible | RestRequestGenerator |
XRR004 |
Error | Several REST attributes | RestRequestGenerator |
XRR005 |
Error | REST request must be partial | RestRequestPartialAnalyzer (code fix: "Make partial") |
XDR001 |
Error | Data record has no usable constructor | DataRecordGenerator |
XDR002 |
Error | Data record column type not supported | DataRecordGenerator |
XDR003 |
Error | Data record type not supported | DataRecordGenerator |
XDR004 |
Error | Concurrency check column not supported | DataRecordGenerator |
XDR005 |
Warning | Generated column cannot be refreshed | DataRecordGenerator |
XDR006 |
Error | Two properties map to one column | DataRecordGenerator |
XDV001 |
Error | Data value has no single scalar value | DataValueGenerator |
XDV002 |
Error | Data value primitive is not a column type | DataValueGenerator |
XDV003 |
Error | Data value type not supported | DataValueGenerator |
XDQ001 |
Error | Argument type must be partial | DataQueryArgsGenerator |
XDQ002 |
Error | Argument type shape not supported | DataQueryArgsGenerator |
XDQ003 |
Error | Int property cannot carry a paging marker | DataQueryArgsGenerator |
XDQ004 |
Error | DataQueryBuilder result is discarded | DataQueryBuilderResultAnalyzer |
XDQ005 |
Error | A compiled statement holds a placeholder | CompiledDataFactoryAnalyzer |
XDQ006 |
Warning | A compiled statement fixes a changing value | CompiledDataFactoryAnalyzer |
XPG001 |
Error | Paged counterpart missing | PagedOperatorGenerator |
XPG002 |
Error | Owning class must be partial | PagedOperatorGenerator |
XPG003 |
Error | Required type not found | PagedOperatorGenerator |
XPG004 |
Error | Operator claimed twice | PagedOperatorGenerator |
π¦ Package Contents
| Namespace | Type |
|---|---|
System.Handlers |
HandlerSourceGenerator |
System.Events |
EventConsumerRegistrationGenerator |
System.Sagas |
SagaRegistrationGenerator |
System.ComponentModel.DataAnnotations |
ValidatorGenerator |
System.Composition |
ServiceRegistrationGenerator |
System.Optionals |
OptionalJsonConverterGenerator |
System.Rests |
RestRequestGenerator, RestRequestPartialAnalyzer (analyzer), RestRequestPartialCodeFix (code fix, Xpandables.Generators.CodeFixes) |
System.Data |
DataRecordGenerator, DataValueGenerator, DataQueryArgsGenerator, DataRepositoryRegistrationGenerator, CompiledQueryOverloadGenerator, DataQueryBuilderResultAnalyzer and CompiledDataFactoryAnalyzer (analyzers), DataQueryBuilderResultCodeFix (code fix, Xpandables.Generators.CodeFixes) |
System.Linq |
PagedOperatorGenerator (gated: runs only when System.AsyncPaged builds) |
The generators target netstandard2.0 and ship under analyzers/dotnet/cs; they are never part of an application's
output.
π License
Apache License 2.0 β see the LICENSE file for details.
<div align="center">
Built with β€οΈ using .NET 11
</div>
Learn more about Target Frameworks and .NET Standard.
This package has no dependencies.
NuGet packages (8)
Showing the top 5 NuGet packages that depend on Xpandables.Generators:
| Package | Downloads |
|---|---|
|
Xpandables.Net
Foundation of the Xpandables libraries: the Result pattern, Optional<T>, ElementCollection, source-generated JSON contexts, decorators, caching, correlation context, text encryption and password hashing; Native AOT compatible. |
|
|
Xpandables.Events
Event-driven architecture: in-process publish/subscribe, event-sourced aggregates and an event store, outbox and inbox with a hosted scheduler, over Xpandables.Data; Native AOT compatible. |
|
|
Xpandables.AspNetCore.Net
ASP.NET Core minimal API integration of the Xpandables libraries: Result to HTTP responses and problem details, endpoint filters, routes, request context, pipeline behaviors and DI extensions; Native AOT compatible. |
|
|
Xpandables.Rests
Declarative REST client: requests described by attributes and completed by source generation, composable request and response pipelines, resilience through Microsoft.Extensions.Http.Resilience; Native AOT compatible. |
|
|
Xpandables.Data
Provider-aware ADO.NET data access: repositories, unit of work and transactions, a typed SQL builder for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, and data records mapped by source generation; Native AOT compatible. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 11.0.0 | 0 | 11/29/2026 |