Search code examples
c#.net-6.0cqrsmediatr

Validator not called after setting up MediatR for .net 6


I am trying to setup CURD in my test project.

I am using latest MediatR nuget library.

services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());

        services.AddMediatR(cfg =>
        {
            cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
            cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>), ServiceLifetime.Transient);
            cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>), ServiceLifetime.Scoped);
        }); 

I have Logging pipeline working when the mediator calls the command. But the validator pipeline never execute. I followed online resources but could not get it to work.

The code was called inside the Program.cs which was a .net API project and have a reference to a Service project where all the Command, Queries, ValidatorBehaviour and LoggingBehaviour was store.

Do anyone have similar setup and able to get the validator working?

I found the reason: I need to add two different validator pipeline

 ValidationBehaviour1<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest

ValidationBehaviour2<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>

Solution

  • If your solution consists of multiple projects, then you should register multiple assemblies (one for each project). Currently, you only register the assembly that contains the code you shared in your posting, via Assembly.GetExecutingAssembly().

    There are multiple ways to get all you project assemblies. One way is to choose a class that is defined in an assembly and do Assembly.GetAssembly(typeof(YourClass)) (and do this for each project).

    Side note:
    MediatR can reshape a repository of code into something that is nice and clean, but it seems that many people bump into the kinds of problems like the one you've just described, even if people had it working once. I have become very excited about IGet, with which you can create MediatR-like structures and clean code, but in my opinion without these kinds of problems.