As per Command Query Separation principle, commands should return void.
I am using MediatR Command Request Handler to create an entity as follows. So how can I get back the created entity?
public class CreateCompanyCommand : IRequest
{
public string Name { get; set; } = default!;
}
public class CreateCompanyHandler : IRequestHandler<CreateCompanyCommand>
{
private readonly IRepository<Company> _repository;
public CreateCompanyHandler(IRepository<Company> repository)
{
_repository = repository;
}
public async Task<Unit> Handle(CreateCompanyCommand request, CancellationToken cancellationToken)
{
var newCompany = new Company(request.Name);
var createdItem = await _repository.AddAsync(newCompany);
return Unit.Value;
}
}
I saw this question as well as its answer here, but I am still not clear.
How can I return the createdItem? What should be the Unit.Value? Can I modify and return something custom on my own instead of Unit.Value?