Skip to main content

DispatcherServiceCollectionExtensions

Namespace: RA.Utilities.Dispatcher.Extensions

The DispatcherServiceCollectionExtensions class registers the core IDispatcher service with the .NET dependency injection container and applies the compile-time handler registrations produced by the package's source generator.

It provides two AddDispatcher extension methods — a parameterless one that applies every auto-registration, and one that takes DispatcherOptions to filter which handlers are registered and to register additional pipeline behaviors and validators. Both are written with a C# 14 extension block — they live inside extension(IServiceCollection services) rather than using the classic this parameter.

// From: /RA.Utilities/Application/RA.Utilities.Dispatcher/Extensions/DispatcherServiceCollectionExtensions.cs

public static class DispatcherServiceCollectionExtensions
{
extension(IServiceCollection services)
{
public IServiceCollection AddDispatcher()
{
ArgumentNullException.ThrowIfNull(services);

return AddDispatcherCore(services, options: null);
}

public IServiceCollection AddDispatcher(Action<DispatcherOptions> configure)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configure);

var options = new DispatcherOptions();
configure(options);

return AddDispatcherCore(services, options);
}
}

private static IServiceCollection AddDispatcherCore(
IServiceCollection services, DispatcherOptions? options)
{
var configuredBehaviors = new List<(Type ServiceType, Type ImplementationType)>();
if (options is not null)
{
AddConfiguredBehaviors(services, options, configuredBehaviors);
AddConfiguredValidators(services, options, configuredBehaviors);
}

int generatedStartIndex = services.Count;
HandlerRegistrations.ApplyAll(services, options);
DispatcherRegistrations.ApplyAll(services);

RemoveGeneratedBehaviorDuplicates(services, generatedStartIndex, configuredBehaviors);

return services;
}
}

The source generator shipped in the package emits a module initializer for every assembly containing IRequestHandler<,> / IRequestHandler<> / INotificationHandler<> implementations and closed pipeline behaviors. Those initializers queue DI registrations (request handlers scoped, notification handlers and behaviors transient) which AddDispatcher() then applies — that is why plain handlers need no explicit AddDispatcher<...> / AddNotification call. The generator also emits the Dispatcher implementation of IDispatcher per assembly — the only dispatcher in the package — and AddDispatcher() applies its registration. See the Auto Registration and Generated Dispatcher guides for the assembly-loading guarantee, dispatch strategy, and diagnostics.

AddDispatcher()​

Applies every queued handler, behavior, and dispatcher registration. This is the call that bootstraps the package — without it there is no IDispatcher, and Send/Publish fail at runtime.

using RA.Utilities.Dispatcher.Extensions;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddDispatcher();

AddDispatcher(Action<DispatcherOptions> configure)​

Applies the queued registrations filtered by the supplied options, and registers the behaviors listed in options.Behaviors and the validators in options.Validators explicitly. Filtering affects source-generated registrations only — handlers registered explicitly, through the fluent builders, through plain DI calls, or through options.Behaviors / options.Validators are untouched.

using RA.Utilities.Dispatcher.Extensions;

builder.Services.AddDispatcher(options =>
{
options.IncludeHandlers = [typeof(CreateOrderHandler)];
options.ExcludeHandlers = [typeof(LegacyOrderImportHandler)];

// Open generic behaviors, registered once for every matching message.
options.Behaviors.Add(typeof(MetricsBehavior<,>));
options.Behaviors.Add(typeof(LoggingBehavior<,>));

// Validator + its ValidationBehavior, registered together.
options.Validators.Add(typeof(CreateOrderCommandValidator), ServiceLifetime.Transient);
});

Internally, configured behaviors and validators are registered first with TryAddEnumerable (so repeated AddDispatcher calls do not duplicate them and they wrap the generated block); HandlerRegistrations.ApplyAll(services, options) then drains and filters the queue in one pass; DispatcherRegistrations.ApplyAll(services) registers the generated Dispatcher itself, which is never filtered. Finally, a generated descriptor for a behavior that was also configured explicitly is removed, so the behavior runs once at its configured (outer) position. See Filtering auto-registered handlers for the inclusion/exclusion rules and DispatcherOptions for the behavior and validator registration rules.

Parameters​

MethodParameterDescription
AddDispatcher()—No parameters. Applies all auto-registrations.
AddDispatcher(Action<DispatcherOptions>)configureReceives a DispatcherOptions instance whose IncludeHandlers / ExcludeHandlers lists decide which auto-registered handlers — and the behaviors related to their messages — are kept, whose Behaviors list registers additional pipeline behaviors explicitly, and whose Validators dictionary registers validators together with their validation behavior.

Both overloads return the same IServiceCollection, so calls chain. The parameterless overload and the fluent AddDispatcher<TRequest, TResponse, THandler>() builder are distinct methods, so both styles can be mixed in one startup sequence.

Why is this important?​

1. Simplifies Setup:​

It provides a clean, discoverable way for a developer using your library to get it working. Instead of needing to know the concrete implementation (Dispatcher), its correct lifetime (Scoped), or the auto-registration queue, they can simply call services.AddDispatcher().

2. Encapsulation:​

It hides the implementation details of the dispatcher pattern. If you were to change the concrete Dispatcher class (or the registration mechanics) in the future, developers using your library wouldn't need to change their startup code as long as the extension method remains.

3. Foundation for Features:​

This registration is the foundation upon which all other features from RA.Utilities.Dispatcher are built. The source generator and the fluent builders (.AddDispatcher<TRequest, TResponse, THandler>(), .AddNotification()) register the handlers and behaviors, while AddDispatcher registers the central "dispatcher" that actually processes the requests and notifications — and applies the auto-discovered handlers.

In short, this class is the essential bootstrapping step required to use the CQRS pattern provided by the RA.Utilities.Dispatcher library.