Mediator Api call failing

Viewed 2011

I'm trying to make a simple request using mediator and .net core. I'm getting an error that I am not understanding. All I'm trying to do is a simple call to get back a guid.

BaseController:

[Route("api/[controller]/[action]")]
[ApiController]
public class BaseController : Controller
{
    private IMediator _mediator;
    protected IMediator Mediator => _mediator ?? (_mediator = HttpContext.RequestServices.GetService<IMediator>());
}

Controller:

// GET: api/Customer/username/password
[HttpGet("{username}/{password}", Name = "Get")]
public async Task<ActionResult<CustomerViewModel>> Login(string username, string password)
{
    return Ok(await Mediator.Send(new LoginCustomerQuery { Username = username,Password = password }));
}

Query:

public class LoginCustomerQuery : IRequest<CustomerViewModel>
{
    public string Username { get; set; }
    public string Password { get; set; }
}

View Model:

 public class CustomerViewModel
 {
     public Guid ExternalId { get; set; }
 }

Handler:

public async Task<CustomerViewModel> Handle(LoginCustomerQuery request, CancellationToken cancellationToken)
{
    var entity = await _context.Customers
        .Where(e =>
        e.Username == request.Username
        && e.Password == Encypt.EncryptString(request.Password))
        .FirstOrDefaultAsync(cancellationToken);
     if (entity.Equals(null))
     {
         throw new NotFoundException(nameof(entity), request.Username);
     }

     return new CustomerViewModel
     {
         ExternalId = entity.ExternalId
     };
 }

This is the exception I am getting: enter image description here

Please let me know what else you need to determine what could be the issue. Also, be kind I have been away from c# for a while.

1 Answers

Thanks for the info it was the missing DI. I added this

// Add MediatR
            services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>));
            services.AddMediatR(typeof(LoginCustomerQueryHandler).GetTypeInfo().Assembly);

and we are good to go.

Related