MediatR 3.0.1 Possible error? Can't get IAsyncRequestHandler to work

When you run IRequest with IAsyncRequestHandler, you receive the following error message.

System.InvalidOperationException: 'No service for type 'MediatR.IRequestHandler`2[TestProject.Domain.Requests.Users.CreateUserRequest,TestProject.Domain.Requests.Users.CreateUserResponse]' has been registered.'

      

This is how I will register it in the startup class

// Add framework services.
services.AddMvc();
services.AddMediatR(typeof(CreateUserRequest).GetTypeInfo().Assembly);

      

CreateUserRequest and Response

public class CreateUserRequest : IRequest<CreateUserResponse>
{
    public string EmailAddress { get; set; }
    public int OrganisationId { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class CreateUserResponse
{
    public int UserId { get; set; }
    public string EmailAddress { get; set; }
}

      

Request handler

public class CreateUserRequestHandler : IAsyncRequestHandler<CreateUserRequest, CreateUserResponse>
{
    private readonly UserManager<User> _userManager;


    public CreateUserRequestHandler()
    {

    }

    public async Task<CreateUserResponse> Handle(CreateUserRequest request)
    {
        //create the user and assign it to the organisation
        var user = new User
        {
            Email = request.EmailAddress,
            OrganisationUsers = new List<OrganisationUser> { new OrganisationUser { OrganisationId = request.OrganisationId } }
        };

        //create new user with password.
        await _userManager.CreateAsync(user, request.Password);

        //create response.
        var response = new CreateUserResponse{UserId = user.Id, EmailAddress = user.Email};

        return response;
    }
}

      

Controller class

public class UserController : Controller
{
    private readonly IMediator _mediator;

    public UserController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<CreateUserResponse> Post(CreateUserRequest request)
    {
        return await _mediator.Send(request);
    }
}

      

the error occurs inside the controller class, it does not end up in the async request handler.

Is there something wrong with registering DI? I went through the examples but couldn't find anything specific to the aspnet core.

+3


source to share





All Articles