jbogard / MediatR

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

Behavior not able to get services with request from minimal api endpoints #1059

Closed Mohs9n closed 3 months ago

Mohs9n commented 3 months ago

I have a behavior for using Fluent validation before requests, when i send a mediatR request through an endpoint inside a controller, it woks fine, but when i send the same request through a minimal api endpoint the request fails to get the validator associated with the requset, it seems to be a service scope issue because when i make the behavior lifetime Scoped another behavior i have (an Authorization behavior) gets resolved and passes, but when i do the same for the validation behavior, the Exception just changes.

        services.AddMediatR(options =>
        {
            options.RegisterServicesFromAssembly(assembly);

            options.AddOpenBehavior(typeof(AuthorizationBehavior<,>), ServiceLifetime.Scoped);
            options.AddOpenBehavior(typeof(ValidationBehavior<,>), ServiceLifetime.Scoped);
        });
        // services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

        services.AddValidatorsFromAssemblyContaining(typeof(DependencyInjection));

Exception before making ValidationBehavior Scoped:

System.InvalidOperationException: Cannot resolve 'System.Collections.Generic.IEnumerable`1[MediatR.IPipelineBehavior`2[TestApplication.Application.Reminders.Commands.SetReminder.SetReminderCommand,ErrorOr.ErrorOr`1[TestApplication.Domain.Reminders.Reminder]]]' from root provider because it requires scoped service 'MediatR.IPipelineBehavior`2[TestApplication.Application.Reminders.Commands.SetReminder.SetReminderCommand,ErrorOr.ErrorOr`1[TestApplication.Domain.Reminders.Reminder]]'.

After:

System.InvalidOperationException: Cannot resolve scoped service 'System.Collections.Generic.IEnumerable`1[MediatR.IPipelineBehavior`2[TestApplication.Application.Reminders.Commands.SetReminder.SetReminderCommand,ErrorOr.ErrorOr`1[TestApplication.Domain.Reminders.Reminder]]]' from root provider.