| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- using AutoMapper;
- using BlackRock.Reporting.API.Core;
- using BlackRock.Reporting.API.Models;
- using MediatR;
-
- namespace BlackRock.Reporting.API.Mediator
- {
- public class CreateUsersCommand : IRequest<Result<Guid>>
- {
- public UserForm User { get; }
- public CreateUsersCommand(UserForm user)
- {
- this.User = user;
- }
- }
-
- public class CreateUsersCommandHandlers : IRequestHandler<CreateUsersCommand, Result<Guid>>
- {
- private readonly ILogger<CreateUsersCommandHandlers> logger;
- private readonly IMapper mapper;
- private readonly IUsersRepository repository;
- private readonly IUnitOfWork unitOfWork;
- public CreateUsersCommandHandlers(ILogger<CreateUsersCommandHandlers> logger, IMapper mapper, IUsersRepository repository, IUnitOfWork unitOfWork)
- {
- this.unitOfWork = unitOfWork;
- this.repository = repository;
- this.mapper = mapper;
- this.logger = logger;
-
- }
- public async Task<Result<Guid>> Handle(CreateUsersCommand command, CancellationToken cancellationToken)
- {
- if (command.User == null)
- throw new ArgumentException($"Parameter {nameof(command.User)} must not be null");
-
- try
- {
- logger.LogInformation("Creating new user ...");
- var user = mapper.Map<UserForm, User>(command.User);
- user.Id = Guid.NewGuid();
- await repository.AddAsync(user);
- await unitOfWork.SaveChangesAsync();
- logger.LogInformation($"User with id {user.Id} has been created successfully");
- return new Result<Guid> { Data = user.Id };
- }
- catch (Exception ex)
- {
- return new Result<Guid> { IsSuccess = false, Error = "Faild to add data to DB." };
- }
- }
- }
- }
|