I have a .Net Core app where i use the .AddMediatR
extension to register the assembly for my commands and handlers following a CQRS approach.
In ConfigureServices in Startup.cs i have used the extension method from the official package MediatR.Extensions.Microsoft.DependencyInjection
with the following parameter:
services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);
The command and commandhandler classes are as follow:
AddEducationCommand.cs
public class AddEducationCommand : IRequest<bool>
{
[DataMember]
public int UniversityId { get; set; }
[DataMember]
public int FacultyId { get; set; }
[DataMember]
public string Name { get; set; }
}
AddEducationCommandHandler.cs
public class AddEducationCommandHandler : IRequestHandler<AddEducationCommand, bool>
{
private readonly IUniversityRepository _repository;
public AddEducationCommandHandler(IUniversityRepository repository)
{
_repository = repository;
}
public async Task<bool> Handle(AddEducationCommand command, CancellationToken cancellationToken)
{
var university = await _repository.GetAsync(command.UniversityId);
university.Faculties
.FirstOrDefault(f => f.Id == command.FacultyId)
.CreateEducation(command.Name);
return await _repository.UnitOfWork.SaveEntitiesAsync();
}
}
When i run the REST endpoint that executes a simple await _mediator.Send(command);
code, i get the following error from my log:
Error constructing handler for request of type MediatR.IRequestHandler`2[UniversityService.Application.Commands.AddEducationCommand,System.Boolean]. Register your handlers withthe container. See the samples in GitHub for examples.
I tried to look through the official examples from the docs without any luck. Does anyone know how i configure MediatR to work properly? Thanks in advance.
I have met the same issue.
The problem is that this line code
services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);
handles all the MediatR IRequest and IRequestHandlers.
but you created an IRepository interface and its implementation class which can't be handled by that MediatR.Extensions.Microsoft.DependencyInjection
so keep all your changes but add this - manually register this like
services.AddScoped(typeof(IUniversityRepository), typeof(UniversitySqlServerRepository));
then issue resolved.