Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue: "No service for type 'MediatR.IRequestHandler'" #1092

Open
AlbertoVPersonal opened this issue Jan 8, 2025 · 0 comments
Open

Issue: "No service for type 'MediatR.IRequestHandler'" #1092

AlbertoVPersonal opened this issue Jan 8, 2025 · 0 comments

Comments

@AlbertoVPersonal
Copy link

Environment

  • Windows 11 Pro
  • .NET8
  • MediatR 12.4.1
  • Console app
  • All classes are in the same assembly

Issue description

I want to use generic handlers with notifications. Due to I was not able to do it, I have changed to generic requests.
And now I'm getting the below error message.

Issue error message

System.InvalidOperationException: No service for type 'MediatR.IRequestHandler`1[NotificationsMediatR.Notifications.GenericBasicTypeNotification`1[System.String]]' has been registered.

Source code

Handlers

public class LocalMediatR
{
    private static LocalMediatR _instance;

    private IMediator _mediator;

    // ...
}

public class HandlerBaseProperties {
  // ...
}

public class BaseNotification : IRequest {
 // ...
}

internal class GenericBasicTypeNotification<T> : BaseNotification { 
 // ...
}

internal class GenericBaseTypeNoResponseHandler<T> : HandlerBaseProperties, IRequestHandler<GenericBasicTypeNotification<T>>
{
    public async Task Handle(GenericBasicTypeNotification<T> request, CancellationToken cancellationToken) {
       // ...
   }
}

Configure services

//...

// Inject MediatR
services.AddMediatR(cfg => {
    cfg.MaxTypesClosing = 0;
    cfg.RegisterGenericHandlers = true;
    cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly);
});

services.AddSingleton<IMediator, Mediator>();
services.AddTransient<BaseWithoutResponseTopicHandler>();
services.AddTransient(typeof(GenericBaseTypeNoResponseHandler<>));
services.AddTransient<GenericBaseTypeNoResponseHandler<string>>(); // Theoretically it is not needed

//...

Configure method

// set the mediatR
var mediatR = LocalMediatR.GetInstance();
mediatR.SetMediatR(mediator);

Example of use and it generates the error

var notif = new GenericBasicTypeNotification<string>()
{
    Payload = "my value"
};
await LocalMediatR.GetInstance().Mediator.Send(notif);

other links read and tests performed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant