You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CreateUserCommand.cs 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using AutoMapper;
  2. using BlackRock.Reporting.API.Core.Interfaces;
  3. using BlackRock.Reporting.API.Core.Models;
  4. using BlackRock.Reporting.API.Mediator.UserMediator.Model;
  5. using MediatR;
  6. namespace BlackRock.Reporting.API.Mediator.UserMediator.Commands
  7. {
  8. public class CreateUserCommand : UserCommand, IRequest<Result<int>>
  9. {
  10. }
  11. public class CreateUserCommandHandlers : IRequestHandler<CreateUserCommand, Result<int>>
  12. {
  13. private readonly ILogger<CreateUserCommandHandlers> logger;
  14. private readonly IMapper mapper;
  15. private readonly IUnitOfWork unitOfWork;
  16. public CreateUserCommandHandlers(ILogger<CreateUserCommandHandlers> logger, IMapper mapper, IUnitOfWork unitOfWork)
  17. {
  18. this.unitOfWork = unitOfWork;
  19. this.mapper = mapper;
  20. this.logger = logger;
  21. }
  22. public async Task<Result<int>> Handle(CreateUserCommand command, CancellationToken cancellationToken)
  23. {
  24. if (command is null)
  25. throw new ArgumentException($"Parameter {nameof(command)} must not be null");
  26. try
  27. {
  28. logger.LogInformation("Creating new user ...");
  29. var user = mapper.Map<UserCommand, User>(command);
  30. await unitOfWork.UsersRepository.AddAsync(user);
  31. await unitOfWork.SaveChangesAsync();
  32. logger.LogInformation($"User with id {user.Id} has been created successfully");
  33. return new Result<int> { Data = user.Id };
  34. }
  35. catch (Exception ex)
  36. {
  37. logger.LogError(ex, "Faild to add data to DB.");
  38. return new Result<int> { IsSuccess = false, Error = "Faild to add data to DB." };
  39. }
  40. }
  41. }
  42. }