jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
10.91k stars 1.16k forks source link

Generic Processors Not Registering Correctly in 12.1.1 #941

Closed ercin-one closed 11 months ago

ercin-one commented 12 months ago
    public class CommandValidationProcessor<TCommand> : IRequestPreProcessor<TCommand> where TCommand : class
    {
        private readonly IValidator<TCommand> _validator;

        public CommandValidationProcessor(IValidator<TCommand> validator)
        {
            _validator = validator;
        }

        public async Task Process(TCommand command, CancellationToken cancellationToken)
        {
            var result = await _validator.ValidateAsync(command, cancellationToken);
            if (!result.IsValid)
            {
                var error = result.Errors.First();
                throw new ApplicationException(Invalid, new(error.ErrorCode, error.ErrorMessage));
            }
        }
    }

Method 1:

        public static IServiceCollection AddApplicationComponents(this IServiceCollection serviceCollection)
        {
            return serviceCollection
                .AddValidation()
                .AddMediatR(configuration =>
                {
                    configuration.RegisterServicesFromAssemblies(AppDomain.CurrentDomain.GetAssemblies());
                })
                .AddScoped(typeof(IRequestPreProcessor<>), typeof(CommandValidationProcessor<>));

        }

Method 2:

        public static IServiceCollection AddApplicationComponents(this IServiceCollection serviceCollection)
        {
            return serviceCollection
                .AddValidation()
                .AddMediatR(configuration =>
                {
                    configuration.RegisterServicesFromAssemblies(AppDomain.CurrentDomain.GetAssemblies());
                    configuration.AddRequestPreProcessor(typeof(CommandValidationProcessor<>));
                });

        }

Both methods are throwing an exception as below: System.ArgumentException: 'Cannot instantiate implementation type 'Company.Framework.Application.Validation.Processors.CommandValidationProcessor1[TCommand]' for service type 'MediatR.Pipeline.IRequestPreProcessor1[TCommand]'.'

jbogard commented 11 months ago

It could be that you don't have a validator registered for that command type.