Table of Contents

Class AutoRegisterAttribute

Namespace
Excalibur.Dispatch
Assembly
Excalibur.Dispatch.Abstractions.dll

Marks a type for compile-time service registration by the source generator.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class AutoRegisterAttribute : Attribute
Inheritance
AutoRegisterAttribute
Inherited Members
Extension Methods

Remarks

When applied to a class, the ServiceRegistrationSourceGenerator will automatically generate DI registration code at compile time. This enables AOT-compatible service registration without runtime reflection.

Example usage:

// Basic registration with default settings (Scoped lifetime, register as self and interfaces)
[AutoRegister]
public class OrderHandler : IDispatchHandler<CreateOrderCommand> { }

// Explicit Singleton lifetime
[AutoRegister(Lifetime = ServiceLifetime.Singleton)]
public class CacheService : ICacheService { }

// Register as concrete type only (no interface registration)
[AutoRegister(AsSelf = true, AsInterfaces = false)]
public class HelperService { }

// Register for interfaces only (not as concrete type)
[AutoRegister(AsSelf = false, AsInterfaces = true)]
public class MultiService : IFirst, ISecond { }

The generated code produces an extension method that can be called at startup:

// In Program.cs or Startup.cs
services.AddGeneratedServices();

AOT Benefits:

  • No runtime reflection - all service discovery at compile time
  • Faster startup - no assembly scanning required
  • Native AOT support - compatible with PublishAot=true
  • Trimming safe - no types unexpectedly removed by IL trimmer

Properties

AsInterfaces

Gets or sets whether to register the type for all implemented interfaces.

public bool AsInterfaces { get; set; }

Property Value

bool

Default is true. When enabled, the service is registered for each interface it implements (e.g., if MyService : IFirst, ISecond, it will be registered for both IFirst and ISecond).

Remarks

System interfaces from System namespace (like IDisposable) are excluded from automatic interface registration.

AsSelf

Gets or sets whether to register the type as itself (concrete type registration).

public bool AsSelf { get; set; }

Property Value

bool

Default is true. When enabled, the service can be resolved by its concrete type (e.g., services.GetRequiredService<MyService>()).

Lifetime

Gets or sets the service lifetime for the registration.

public ServiceLifetime Lifetime { get; set; }

Property Value

ServiceLifetime

Default is Scoped. Per .NET Core conventions, Scoped is the safest default for most services as it provides proper request isolation while avoiding common singleton pitfalls.