# Command Registration How to register command handlers in dependency injection. ## Basic Registration ### Command with Result ```csharp builder.Services.AddCommand(); ``` **This registers:** - Handler as `ICommandHandler` - Metadata for endpoint discovery - Scoped lifetime (default) ### Command without Result ```csharp builder.Services.AddCommand(); ``` ## Registration with Validator ```csharp builder.Services.AddCommand(); ``` **This registers:** - Handler - Validator as `IValidator` - Metadata ## Registration with Workflow ```csharp builder.Services.AddCommandWithWorkflow(); ``` For event-emitting commands. ## Service Lifetimes ### Scoped (Default - Recommended) ```csharp services.AddCommand(); // Handler is Scoped ``` **Characteristics:** - One instance per request - Can inject DbContext - Disposed after request ### Custom Lifetime ```csharp // Transient services.AddTransient, CreateUserCommandHandler>(); // Singleton (not recommended - can't inject DbContext) services.AddSingleton, CreateUserCommandHandler>(); ``` ## Bulk Registration ### Extension Methods ```csharp // Extensions/ServiceCollectionExtensions.cs public static class ServiceCollectionExtensions { public static IServiceCollection AddUserCommands(this IServiceCollection services) { services.AddCommand(); services.AddCommand(); services.AddCommand(); return services; } public static IServiceCollection AddOrderCommands(this IServiceCollection services) { services.AddCommand(); services.AddCommand(); return services; } } // Usage in Program.cs builder.Services.AddUserCommands(); builder.Services.AddOrderCommands(); ``` ### Module Pattern ```csharp public interface IModule { void RegisterServices(IServiceCollection services); } public class UserModule : IModule { public void RegisterServices(IServiceCollection services) { // Commands services.AddCommand(); services.AddCommand(); // Queries services.AddQuery(); // Services services.AddScoped(); } } // Auto-register all modules var modules = typeof(Program).Assembly .GetTypes() .Where(t => typeof(IModule).IsAssignableFrom(t) && !t.IsInterface) .Select(Activator.CreateInstance) .Cast(); foreach (var module in modules) { module.RegisterServices(builder.Services); } ``` ## Organizing Registrations ### By Feature ``` Program.cs Extensions/ UserServiceRegistration.cs OrderServiceRegistration.cs ProductServiceRegistration.cs ``` ### By Layer ``` Program.cs Extensions/ CommandRegistration.cs QueryRegistration.cs RepositoryRegistration.cs ``` ## See Also - [Dependency Injection](../../architecture/dependency-injection.md) - DI patterns - [Modular Solution Structure](../../architecture/modular-solution-structure.md)