| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- using AutoMapper;
- using BlackRock.Reporting.API.Core;
- using BlackRock.Reporting.API.Mediator.Model;
- using BlackRock.Reporting.API.Models;
- using MediatR;
-
- namespace BlackRock.Reporting.API.Mediator
- {
- public class CreateUsersCommand : UserCommand, IRequest<Result<int>>
- {
- public CreateUsersCommand(string Name, string Email) : base(Name, Email)
- {
- }
- }
-
- public class CreateUsersCommandHandlers : IRequestHandler<CreateUsersCommand, Result<int>>
- {
- private readonly ILogger<CreateUsersCommandHandlers> logger;
- private readonly IMapper mapper;
- private readonly IUnitOfWork unitOfWork;
- public CreateUsersCommandHandlers(ILogger<CreateUsersCommandHandlers> logger, IMapper mapper, IUnitOfWork unitOfWork)
- {
- this.unitOfWork = unitOfWork;
- this.mapper = mapper;
- this.logger = logger;
-
- }
- public async Task<Result<int>> Handle(CreateUsersCommand 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." };
- }
- }
- }
- }
|