using AutoMapper; using BlackRock.Reporting.API.Core; using BlackRock.Reporting.API.Models; using MediatR; namespace BlackRock.Reporting.API.Mediator { public class CreateUsersCommand : IRequest> { public UserForm User { get; } public CreateUsersCommand(UserForm user) { this.User = user; } } public class CreateUsersCommandHandlers : IRequestHandler> { private readonly ILogger logger; private readonly IMapper mapper; private readonly IUsersRepository repository; private readonly IUnitOfWork unitOfWork; public CreateUsersCommandHandlers(ILogger logger, IMapper mapper, IUsersRepository repository, IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; this.repository = repository; this.mapper = mapper; this.logger = logger; } public async Task> 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(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 { Data = user.Id }; } catch (Exception ex) { return new Result { IsSuccess = false, Error = "Faild to add data to DB." }; } } } }