INNVTV
INNVTV

Reputation: 3367

MediatR setup for shared Class Library in Console vs WebAPI

I have a .Net Core 2.2 class library that uses the CQRS pattern with MediatR. I add all my dependencies into a serviceProvider in Main and attach MediatR via:

serviceCollection.AddMediatR();
var serviceProvider = serviceCollection.BuildServiceProvider();

Everything works like a charm and I am able to send any of my commands or queries to MediatR without fail.

I want to use the same exact library in a WebApi (also .Net Core 2.2) and set up my serviceProvider the exact same way inside of the Startup.ConfigureServices() method and I get the following exception when calling any controller that uses MediatR:

InvalidOperationException: Handler was not found for request of type MediatR.IRequestHandler`2[Core.Application.Accounts.Queries.GetAccountListQuery,System.Collections.Generic.List`1[Core.Application.Accounts.Models.AccountViewModel]]. Register your handlers with the container. See the samples in GitHub for examples. MediatR.Internal.RequestHandlerBase.GetHandler(ServiceFactory factory)

I was able to resolve the issue by explicitly adding each command or query prior to adding MediatR to the DI container:

services.AddMediatR(typeof(GetAccountListQuery).GetTypeInfo().Assembly);
services.AddMediatR();

But does this mean I have to register every single IRequest object in my library? How is MediatR able to register them for me in the Console app but not in the WebAPI? Is there a better method?

I have seen this post that recommends assembly scanning, however it perplexes me that my Console app seemed to do this automatically. Also I am not sure I want to move to Autofac just yet. I have seen some packages to help you do the same with the default ServiceProvider - however I really want to avoid adding extra dependencies unless absolutely necessary.

Upvotes: 3

Views: 4860

Answers (1)

Dmitry Pavlov
Dmitry Pavlov

Reputation: 28290

It should be enough to just have this:

services.AddMediatR(typeof(GetAccountListQuery));

or just

services.AddMediatR(typeof(Startup));

It works for me in ASP.NET Core 2.2. The project has these two NuGet dependencies:

P.S. For those, who minuses - any class from assembly would work. I used GetAccountListQuery as an example because it is for sure inside the right assembly. See my comments below.

Upvotes: 4

Related Questions