DI Integration - BisocM/CQRSharp GitHub Wiki

Service Registration

Use the provided extension method to register the dispatcher, handlers, and pipeline behaviors.

services.AddCQRS(options =>
{
    options.RunMode = RunMode.Async;
});

Major Service Lifetimes

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.

Examples

Defining a Command

[Validate]
public class UpdateUserCommand : CommandBase
{
    public Guid UserId { get; set; }
    public string Email { get; set; }
}

Implementing a Command Handler

public class UpdateUserCommandHandler : ICommandHandler<UpdateUserCommand>
{
    public Task<CommandResult> Handle(UpdateUserCommand command, CancellationToken cancellationToken)
    {
        // Update user logic
        return Task.FromResult(CommandResult.Success);
    }
}

Defining a Query

public class GetAllUsersQuery : QueryBase<List<UserDto>>
{
    // Any query parameters
}

Implementing a Query Handler

public class GetAllUsersQueryHandler : IQueryHandler<GetAllUsersQuery, List<UserDto>>
{
    public Task<List<UserDto>> Handle(GetAllUsersQuery query, CancellationToken cancellationToken)
    {
        // Retrieve users
        return Task.FromResult(new List<UserDto> { /* ... */ });
    }
}

⚠️ **GitHub.com Fallback** ⚠️