Skip to main content
Version: 3.x

Source Generator

UnambitiousFx.Synapse.Generator is a Roslyn incremental source generator that reads your handler class attributes and emits a registration class at compile time. This eliminates manual RegisterRequestHandler / RegisterEventHandler calls and makes the codebase NativeAOT-compatible by capturing dispatch delegates without reflection.

Install​

dotnet add package UnambitiousFx.Synapse.Generator

No further setup is needed — the generator runs automatically during the build.

Mark your handlers​

Annotate each handler class with the corresponding attribute:

[RequestHandler<TRequest, TResponse>] — for IRequest<TResponse>​

using UnambitiousFx.Synapse.Abstractions;

[RequestHandler<CreateTaskCommand, Guid>]
public class CreateTaskHandler : IRequestHandler<CreateTaskCommand, Guid>
{
public async ValueTask<Result<Guid>> HandleAsync(CreateTaskCommand cmd, CancellationToken ct = default)
{
// ...
return Result.Success(Guid.NewGuid());
}
}

[RequestHandler<TRequest>] — for IRequest (no response)​

[RequestHandler<DeleteTaskCommand>]
public class DeleteTaskHandler : IRequestHandler<DeleteTaskCommand>
{
public async ValueTask<Result> HandleAsync(DeleteTaskCommand cmd, CancellationToken ct = default)
{
// ...
return Result.Success();
}
}

[EventHandler<TEvent>] — for IEventHandler<TEvent>​

[EventHandler<TaskCreatedEvent>]
public class AuditTaskCreated : IEventHandler<TaskCreatedEvent>
{
public ValueTask<Result> HandleAsync(TaskCreatedEvent @event, CancellationToken ct = default)
{
// ...
return ValueTask.FromResult(Result.Success());
}
}

[StreamRequestHandler<TRequest, TItem>] — for IStreamRequestHandler<TRequest, TItem>​

[StreamRequestHandler<StreamTasksQuery, TaskDto>]
public class StreamTasksQueryHandler : IStreamRequestHandler<StreamTasksQuery, TaskDto>
{
public async IAsyncEnumerable<Result<TaskDto>> HandleAsync(
StreamTasksQuery query,
[EnumeratorCancellation] CancellationToken ct = default)
{
// ...
yield return Result.Success(new TaskDto());
}
}

Generated class​

By default the generator produces one class named RegisterGroup in your assembly's root namespace — the MSBuild RootNamespace property (which may differ from the assembly name, e.g. assembly App with <RootNamespace>Company.App</RootNamespace>). Prefer a specific namespace, name, or accessibility? See Customize the generated class below.

RegisterGroup​

Implements both IRegisterGroup and IEventDispatcherRegistration. Contains one RegisterXxxHandler<...>() call per annotated handler, plus one AOT-safe dispatch delegate per IEvent type found in the assembly:

// Generated — do not edit
public sealed class RegisterGroup : IRegisterGroup, IEventDispatcherRegistration
{
public void Register(IDependencyInjectionBuilder builder)
{
builder.RegisterRequestHandler<CreateTaskHandler, CreateTaskCommand, Guid>();
builder.RegisterRequestHandler<DeleteTaskHandler, DeleteTaskCommand>();
builder.RegisterEventHandler<AuditTaskCreated, TaskCreatedEvent>();
builder.RegisterStreamRequestHandler<StreamTasksQueryHandler, StreamTasksQuery, TaskDto>();
}

public void RegisterDispatchers(Action<Type, DispatchEventDelegate> register)
{
register(
typeof(TaskCreatedEvent),
static (e, dispatcher, ct) => dispatcher.DispatchAsync((TaskCreatedEvent)e, ct));
}
}

Wire up the generated class​

Pass the generated class to AddSynapse:

services.AddSynapse(cfg =>
{
cfg.AddRegisterGroup(new RegisterGroup());
});

AddRegisterGroup automatically detects that RegisterGroup implements IEventDispatcherRegistration and registers the AOT-safe dispatch delegates — no second call needed.

:::caution NativeAOT requirement RegisterGroup implements IEventDispatcherRegistration, so the single AddRegisterGroup call is sufficient for NativeAOT. Without the source generator, event dispatch falls back to runtime typeof(T) resolution which the AOT compiler cannot analyze. :::

Customize the generated class​

To choose the namespace, name, or accessibility of the generated class, declare your own partial class and mark it with [RegisterGroup]. The generator then fills that class in as a partial — implementing IRegisterGroup and IEventDispatcherRegistration — instead of emitting the default RegisterGroup in the root namespace:

using UnambitiousFx.Synapse.Abstractions;

namespace Company.App.Composition;

[RegisterGroup]
public partial class AppRegistrations; // the generator supplies the implementation

Wire it up by its own name:

services.AddSynapse(cfg =>
{
cfg.AddRegisterGroup(new AppRegistrations());
});

Rules:

  • The class must be a top-level, non-generic partial class (diagnostics MDG016/MDG017 otherwise).
  • Declare at most one [RegisterGroup] class per assembly (diagnostic MDG015 otherwise).
  • The generator emits no accessibility modifier on its partial, so the visibility (public, internal, …) is whatever you declare on your own partial.

When no [RegisterGroup] class is present, the default public sealed class RegisterGroup in the root namespace is generated as shown above.

Incremental generation​

The generator is an IIncrementalGenerator — it only re-generates when a handler class is added, removed, or its attributes change. Build times are not affected significantly in large solutions.

Diagnostics​

The same UnambitiousFx.Synapse.Generator package also ships Roslyn analyzers. They report registration mistakes at compile time and all five default to Warning. SYN103 is live in the editor. SYN101, SYN102, SYN104 and SYN105 are compilation-end analyzers: they need the whole assembly, so they report on a build or a full-solution analysis rather than as you type.

IDWhen it firesFix
SYN101A request type (IRequest or IRequest<TResponse>) declared in this assembly has no handler in this assembly. Events and stream requests are not checked. A contracts-only assembly (requests without handlers) warns once per request, so set dotnet_diagnostic.SYN101.severity = none there.Add a handler class with the matching [RequestHandler...] attribute, or disable the rule if the handler lives in another project.
SYN102A [PipelineBehavior] behavior (or an [assembly: SynapseGlobalBehavior(...)] entry) applies to no handler visible from this assembly (for example its generic constraint matches no request), so it never runs. A [PipelineBehavior] in a shared library with no handlers of its own is inert in the consuming host too (see modular monolith), so the warning is real. Global entries whose behavior type comes from a referenced assembly are not reported.Widen or correct the constraint, or delete the behavior. For a shared library, declare [assembly: SynapseGlobalBehavior(typeof(...))] in the composition root instead.
SYN103A handler attribute is placed on a record. The generator ignores records, so the handler is not registered.Declare the handler as a class.
SYN104A class implements a handler interface but has no handler attribute, in an assembly that uses the attributes elsewhere.Add the attribute, or register the handler manually and silence the rule for that class with #pragma warning disable SYN104.
SYN105[assembly: SynapseGlobalBehavior(...)] is declared and this assembly calls AddSynapse(...) (so it is a composition root), but no AddRegisterGroup(...) call registers this assembly's own generated group — the attribute is accepted and the behavior never runs, with no error anywhere else. An assembly that declares the attribute with no AddSynapse(...) call of its own (a shared library, not a host) is not reported: the attribute is inert there regardless, since assembly attributes are not inherited by referencing assemblies.Register this assembly's own generated group: cfg.AddRegisterGroup(new <ThisAssembly>.RegisterGroup()) (or your [RegisterGroup] partial's name), alongside the other groups.

The generator itself also reports two errors about behavior ordering declared with [PipelineBehavior(Stage = ..., Before = ..., After = ...)]:

IDWhen it firesFix
MDG018The Before/After constraints of several behaviors form a cycle, so no pipeline containing them can be ordered. Reported on each behavior of the cycle.Remove one of the constraints.
MDG019A constraint contradicts two declared stages (a Validation behavior declared Before an Observability one), or a behavior names itself in Before/After.Change a stage or drop the constraint.

What depends on a runtime Order (the stage a behavior without a declared stage falls in) is checked at startup by ValidateSynapse() instead (SYN005, SYN006).

Disable a rule per project or per folder with an .editorconfig entry:

[*.cs]
dotnet_diagnostic.SYN101.severity = none

Two limits to keep in mind:

  • SYN101 only sees the current assembly. A request whose handler is in another project needs the rule disabled in the project that declares the request.
  • SYN104 cannot see manual registration. A handler you register by hand with RegisterRequestHandler or RegisterEventHandler is still reported when it has no attribute; silence it per class with #pragma warning disable SYN104, or disable the rule.

The analyzers work at compile time and complement the runtime ValidateSynapse() check. SYN105 catches the [assembly: SynapseGlobalBehavior] case of this (issue #91): a plain handler group that is never registered at all is a different, louder failure — it fails at the first dispatch attempt instead of staying silent, so no analyzer is needed for it.

See also​