DI Integration - BisocM/CQRSharp GitHub Wiki
Use the provided extension method to register the dispatcher, handlers, and pipeline behaviors.
services.AddCQRS(options =>
{
options.RunMode = RunMode.Async;
});
Service Type | Interface | Lifetime | Description |
---|---|---|---|
Handlers | ICommandHandler<TCommand> |
Transient | Handlers are stateless and are created each time they are requested. |
IQueryHandler<TQuery, TResult> |
Transient | Handlers are stateless and are created each time they are requested. | |
Dispatcher | IDispatcher |
Singleton | The dispatcher is shared across the application's lifetime, ensuring a single instance exists throughout the application. |
Pipeline Behaviors | IPipelineBehavior<TRequest, TResult> |
Transient | Pipeline behaviors are stateless and created on each request in the pipeline. |
EventManager | EventManager |
Singleton | The EventManager is shared across the application, responsible for managing events like query completion. |
Attributes | Attributes are not registered with the DI container | N/A | Attributes are instantiated via reflection but receive an IServiceProvider parameter, allowing them to resolve services within their methods. |
[Validate]
public class UpdateUserCommand : CommandBase
{
public Guid UserId { get; set; }
public string Email { get; set; }
}
public class UpdateUserCommandHandler : ICommandHandler<UpdateUserCommand>
{
public Task<CommandResult> Handle(UpdateUserCommand command, CancellationToken cancellationToken)
{
// Update user logic
return Task.FromResult(CommandResult.Success);
}
}
public class GetAllUsersQuery : QueryBase<List<UserDto>>
{
// Any query parameters
}
public class GetAllUsersQueryHandler : IQueryHandler<GetAllUsersQuery, List<UserDto>>
{
public Task<List<UserDto>> Handle(GetAllUsersQuery query, CancellationToken cancellationToken)
{
// Retrieve users
return Task.FromResult(new List<UserDto> { /* ... */ });
}
}