CQRSSharp is a lightweight and extensible .NET library that implements the Command Query Responsibility Segregation (CQRS) pattern. It simplifies the separation of read and write logic with clean interfaces for commands and queries, offering better code organization, testability, and scalability — all without the overhead of reflection.
$ dotnet add package CQRSSharpA lightweight CQRS (Command Query Responsibility Segregation) implementation built on top of a mediator-like dispatcher pattern for clean and scalable architecture in .NET 9+ projects.
Install via NuGet:
dotnet add package CQRSSharp --version 1.0.0
YourProject/
├── Application/
│ ├── Commands/
│ │ └── CreateContactCommand.cs
│ ├── Queries/
│ │ └── GetContactsQuery.cs
│ ├── Handlers/
│ │ ├── CreateContactHandler.cs
│ │ └── GetContactsHandler.cs
│ └── Behaviors/
│ ├── RequestLoggingPipelineBehavior.cs
│ └── EnrichResponseBehavior.cs
├── API/
│ └── Controllers/
│ └── ContactController.cs
├── Domain/
│ └── Interfaces/
│ └── IContactService.cs
[Route("api/contact")]
[ApiController]
public class ContactController(IDispatcher dispatcher) : ControllerBase
{
[Route("get-contacts")]
[HttpGet]
public async Task<IActionResult> GetContacts()
{
return Ok(await dispatcher.SendAsync(new GetContactsQuery { }));
}
}
public class CreateContactCommand : IRequest<Result>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Mobile { get; set; }
public string? Email { get; set; }
public string CountryCode { get; set; }
}
public class GetContactsQuery : IRequest<Result>
{
}
public class CreateContactHandler(IContactService contactService)
: IRequestHandler<CreateContactCommand, Result>
{
public async Task<Result> HandleAsync(CreateContactCommand command, CancellationToken cancellationToken)
{
var result = await contactService.CreateContactsAsync(command);
return Result.Success(result);
}
}
public static void AddApplication(this IServiceCollection services)
{
services.AddCQRS(cfg =>
{
cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
cfg.AddOpenBehavior(typeof(RequestLoggingPipelineBehavior<,>));
cfg.AddOpenBehavior(typeof(EnrichReponseBehavior<,>));
});
}
This project is licensed under the MIT License.
Kishan Suthar