Skip to content

A CQRS Project using a DDD structure without MediatR library

Notifications You must be signed in to change notification settings

Leanwit/dotnet-cqrs

Repository files navigation

dotnet-cqrs

This project shows a clean way to use CQRS without using the MediatR library.

In C# is common to use a library named MediatR to implement CQRS. This is an amazing library but forces you to implement the interface INotification, INotificationHandler and IRequestHandler<T1,T2> in your domain/application layer coupling this with an infrastructure library. This is a different approach to avoid add this coupling.

Commands

A command example

public class CreateItemCommand : Command
{    
    public CreateItemCommand(Guid id, string name) 
    {
        Id = id;
        Name = name;
    }
}

A handler example

public class CreateItemCommandHandler : CommandHandler<CreateItemCommand>
{
    private readonly ItemRepository _repository;

    public CreateItemCommandHandler(ItemRepository repository)
    {
        _repository = repository;
    }

    public async Task Handle(CreateItemCommand command)
    {
        await _repository.Add(new Item(command.Id, command.Name));
    }
}

Interfaces to add in Domain Layer

Command Interfaces

Queries

A query example:

public class FindItemQuery : Query
{
    public Guid Id { get; private set; }

    public FindItemQuery(Guid id)
    {
        Id = id;
    }
}

A handler example

public class FindItemQueryHandler : QueryHandler<FindItemQuery, ItemResponse>
{
    private readonly ItemRepository _repository;

    public FindItemQueryHandler(ItemRepository repository)
    {
        _repository = repository;
    }

    public async Task<ItemResponse> Handle(FindItemQuery query)
    {
        Item item = await _repository.GetById(query.Id);
        
        return new ItemResponse(item.Id, item.Name, item.IsCompleted);
    }
}

Interfaces to add in Domain Layer

Query Interfaces

InMemoryBus implementation

InMemoryCommandBus

InMemoryQueryBus

Dependency Injection

Command

services.AddScoped<CommandHandler<CreateItemCommand>, CreateItemCommandHandler>();

Query

services.AddScoped<QueryHandler<FindItemQuery, ItemResponse>, FindItemQueryHandler>();

Automatic Load

services.AddCommandServices(typeof(Command).Assembly);
services.AddQueryServices(typeof(Query).Assembly);

About

A CQRS Project using a DDD structure without MediatR library

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages