47 lines
1.7 KiB
C#
47 lines
1.7 KiB
C#
using MediatR;
|
|
using MyService.Domain.AggregatesModel.SampleAggregate;
|
|
|
|
namespace MyService.API.Application.Commands;
|
|
|
|
/// <summary>
|
|
/// EN: Handler for CreateSampleCommand.
|
|
/// VI: Handler cho CreateSampleCommand.
|
|
/// </summary>
|
|
public class CreateSampleCommandHandler : IRequestHandler<CreateSampleCommand, CreateSampleCommandResult>
|
|
{
|
|
private readonly ISampleRepository _sampleRepository;
|
|
private readonly ILogger<CreateSampleCommandHandler> _logger;
|
|
|
|
public CreateSampleCommandHandler(
|
|
ISampleRepository sampleRepository,
|
|
ILogger<CreateSampleCommandHandler> logger)
|
|
{
|
|
_sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
public async Task<CreateSampleCommandResult> Handle(
|
|
CreateSampleCommand request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation(
|
|
"Creating new sample with name: {Name} / Tạo sample mới với tên: {Name}",
|
|
request.Name);
|
|
|
|
// EN: Create domain entity / VI: Tạo domain entity
|
|
var sample = new Sample(request.Name, request.Description);
|
|
|
|
// EN: Add to repository / VI: Thêm vào repository
|
|
_sampleRepository.Add(sample);
|
|
|
|
// EN: Save changes (dispatches domain events) / VI: Lưu thay đổi (dispatch domain events)
|
|
await _sampleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
|
|
|
_logger.LogInformation(
|
|
"Sample created successfully with ID: {SampleId} / Sample đã tạo thành công với ID: {SampleId}",
|
|
sample.Id);
|
|
|
|
return new CreateSampleCommandResult(sample.Id);
|
|
}
|
|
}
|