Skip to main content

Auto Registration

Handlers do not need to be registered one by one. A source generator shipped inside the RA.Utilities.Dispatcher NuGet package discovers handler and behavior implementations at compile time and emits the registration code for you — plain handlers and closed pipeline behaviors are wired up with nothing more than the parameterless services.AddDispatcher() (distinct from the fluent AddDispatcher<TRequest, TResponse, THandler>() overloads).

🎯 How It Works​

The generator ships as an analyzer inside the RA.Utilities.Dispatcher package (analyzers/dotnet/cs), so every consumer of the NuGet package gets it automatically — no extra package reference, attribute, or configuration required.

For each assembly that references the package, the generator:

  1. Scans the assembly for every non-abstract, non-static class implementing one of the handler or behavior contracts:
    • IRequestHandler<TRequest, TResponse> (request with response)
    • IRequestHandler<TRequest> (request without response)
    • INotificationHandler<TNotification> (notification subscriber)
    • IPipelineBehavior<TRequest, TResponse> / IPipelineBehavior<TRequest> (request pipeline behaviors)
    • INotificationBehavior<TNotification> (notification pipeline behaviors)
  2. Validates each candidate (see diagnostics below).
  3. Emits a module initializer into that assembly that queues the registrations on a static queue in the RA.Utilities.Dispatcher runtime (RA.Utilities.Dispatcher.Generated.HandlerRegistrations): handlers under their interfaces and as themselves (so the generated dispatcher can inject them by concrete type), behaviors under their behavior interfaces.
  4. When your startup code calls services.AddDispatcher(), all queued registrations are applied to the service collection in one pass.
var builder = WebApplication.CreateBuilder(args);

// Registers IDispatcher AND applies every compile-time handler registration
// queued by the source generator.
builder.Services.AddDispatcher();

No AddDispatcher<...>() or AddNotification<...>() calls are needed for plain handlers.

🔍 Discovery Rules​

The generator inspects the whole class hierarchy: matching interfaces are detected through AllInterfaces, so a concrete class that inherits from an abstract base (which itself implements the interface) is registered as itself, not as the base.

ScenarioBehavior
Abstract class implementing a handler interfaceSkipped — it is a base class, not a registrable handler
Concrete class implementing a handler interface directlyAuto-registered
Concrete class deriving from an abstract handler baseAuto-registered as the concrete class
Concrete class implementing multiple handler interfacesOne registration per implemented interface
Partial classSingle registration (parts are de-duplicated)
Generic handler class (MyHandler<T>)DSAG002 warning — skipped; register explicitly
private / file-local handler (or contained in one)DSAG003 error
struct handlerDSAG004 error
Two handlers for the same request pair in one assemblyDSAG005 error
Multiple notification handlers for the same notificationAllowed — fan-out is their purpose
Closed (non-generic) behavior classAuto-registered under its behavior interface (transient) — resolved by the generated dispatcher through DI
Generic behavior class (MyBehavior<TRequest, TResponse>)DSAG010 warning — skipped; register it with DispatcherOptions.Behaviors or AddDecoration
Multiple behaviors for the same messageAllowed — composed in registration order; use [PipelineBehaviorOrder] to pin the position

🛠️ Diagnostics​

All diagnostics use the category RA.Utilities.Dispatcher.Generators:

IDSeverityMeaning
DSAG001WarningCompilation targets a framework before .NET 5, where ModuleInitializerAttribute does not exist, so handlers cannot be auto-registered. Register handlers explicitly with AddDispatcher / AddNotification.
DSAG002WarningHandler is generic, so the generated registration code cannot supply a type argument. Register it explicitly.
DSAG003ErrorHandler (or one of its containing types) is private or file-local, so the generated code cannot reference it. Make it internal/public (or register explicitly).
DSAG004ErrorHandler is a struct. Handlers are registered and resolved as class services.
DSAG005ErrorTwo or more handlers implement the same request handler pair (IRequestHandler<TRequest, TResponse> or IRequestHandler<TRequest>) in one assembly — the winning registration would be load-order dependent. A request may have exactly one handler; remove one of the implementations.
DSAG010WarningPipeline behavior is generic — it is not auto-registered. Register it with DispatcherOptions.Behaviors (open generic, once for every message) or AddDecoration (per request); the generated dispatcher resolves explicitly registered behaviors from DI.

The generator reports additional message and handler diagnostics — DSAG006–DSAG009 — see Generated Dispatcher diagnostics.

⏳ Lifetimes​

Generated registrations use the same lifetimes as the explicit fluent builders:

RegistrationLifetime
IRequestHandler<TRequest, TResponse> → handlerScoped
IRequestHandler<TRequest> → handlerScoped
INotificationHandler<TNotification> → handlerTransient
Handler as its concrete type (for the generated dispatcher's direct injection)Same as the interface registration
Behavior under its interface (IPipelineBehavior<,> / IPipelineBehavior<> / INotificationBehavior<>)Transient

Registering handlers as themselves is what lets the generated Send resolve PingHandler directly and call it without interface dispatch — see Generated Dispatcher.

🎛️ Filtering Auto-Registered Handlers​

AddDispatcher has an options overload that filters which discovered handlers — and the pipeline/notification behaviors related to the messages they handle — are registered:

using RA.Utilities.Dispatcher.Options;

builder.Services.AddDispatcher(options =>
{
// If null, ignored. If set, only these handlers (and their related behaviors) register.
options.IncludeHandlers = [typeof(CreateOrderHandler)];

// If null, ignored. If set, these handlers (and their related behaviors) do not register.
options.ExcludeHandlers = [typeof(LegacyImportHandler)];
});
RuleBehavior
IncludeHandlersnull — ignored. Set — only the listed types register, plus the behaviors related to the messages they handle.
ExcludeHandlersnull — ignored. Set — the listed types do not register, nor do the behaviors related to their messages once no registered handler handles them.
Behavior typesBoth lists also accept behavior types: a listed behavior is kept or removed directly.
PrecedenceExclusions win over inclusions.
Request behaviorsRemoved together with the handler of their request (a behavior whose request has no handler at all is left alone unless IncludeHandlers is set).
Notification behaviorsKept while at least one handler for the notification remains.
ScopeFilters the source-generated registrations only. Explicit AddDispatcher<TRequest, TResponse, THandler>() / AddNotification<TNotification>() / AddDecoration<TBehavior>() registrations, behaviors listed in DispatcherOptions.Behaviors, and validators registered through DispatcherOptions.Validators are untouched.

The filter runs at startup, right after the queued registrations are applied: the descriptors added by HandlerRegistrations.ApplyAll are examined, and the ones that belong to filtered-out handlers (and their behaviors) are removed from the service collection. See DispatcherOptions for the property reference.

🧩 Registering Generic Behaviors in Bulk​

Generic behaviors are not auto-registered, but the options overload can register them once for the whole application. Use Behaviors for open generic types (and for closed behaviors you want to place outside the generated block); use AddDecoration when only one request should be decorated:

builder.Services.AddDispatcher(options =>
{
options.Behaviors.Add(typeof(MetricsBehavior<,>)); // open generic — every request
options.Behaviors.Add(typeof(LoggingBehavior<,>)); // runs inside metrics
});

The list order is the chain order (first = outermost), the types are registered before the generated block, duplicates are suppressed with TryAddEnumerable, and a closed behavior that is also auto-discovered runs exactly once at its configured position. See DispatcherOptions for the full rules.

📥 Assembly-Loading Guarantee​

Module initializers run when their assembly is loaded by the CLR. The registrations are queued at that moment and applied later, when AddDispatcher() executes.

The practical guarantee is:

Auto-registration covers the assembly that calls AddDispatcher() plus any assembly that was already loaded before that call.

// Program.cs — entry assembly: handlers here are always registered ✓
builder.Services.AddDispatcher();

Referenced class libraries load lazily on the CLR — a library's module initializer does not run just because the library is referenced. If a handler lives in a library whose types are first touched only when a request arrives (i.e., after AddDispatcher() has already applied the queue), that handler may be registered too late.

Escape hatches​

Keep handlers where they are guaranteed to be registered, or force the assembly to load early:

  1. Keep handlers in the entry / composition assembly — the assembly that calls AddDispatcher(). This is the simplest and recommended layout.
  2. Touch the handler assembly at startup — reference one of its types before (or when) calling AddDispatcher(), forcing the CLR to load it:
_ = typeof(SomeHandlerInTheLibrary).Assembly; // force assembly load
builder.Services.AddDispatcher();
  1. Register explicitly — handlers in lazily-loaded libraries can always be registered the classic way:
builder.Services.AddDispatcher<MyCommand, MyResponse, MyHandlerInAnotherLibrary>();
builder.Services.AddNotification<OrderPlaced>().AddHandler<MyNotificationHandlerInAnotherLibrary>();

🧩 What Still Needs Explicit Registration​

The generator discovers handlers and closed behaviors. Everything else is registered explicitly:

ComponentRegistration
Request handlers (plain, non-generic, in an early-loaded assembly)Automatic
Notification handlers (plain, non-generic, in an early-loaded assembly)Automatic
Closed pipeline behaviors (IPipelineBehavior<,> / IPipelineBehavior<> / INotificationBehavior<>)Automatic — under their interfaces, resolved by the generated dispatcher through DI
Generic handlersAddDispatcher<TRequest, TResponse, THandler>() / AddNotification<TNotification>().AddHandler<THandler>() (generator emits DSAG002)
Generic behaviorsDispatcherOptions.Behaviors for bulk/open generic registration, or .AddDecoration<TBehavior>() for one request (generator emits DSAG010)
Validators (IValidator<T>)DispatcherOptions.Validators for bulk registration with the inferred ValidationBehavior, or .AddValidator<TValidator>() per request
Handlers with custom lifetimes or setupManual DI registration

If a request handler is registered both automatically and explicitly, the registrations simply stack; keep only the explicit one when you need a custom setup.