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