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.

CreateUsersCommand.cs 1.9KB

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