Search code examples
c#.net-6.0mediatr

MediatR registiring query class in different class library not working


Using mediatr fresh .net6 project and everything works fine except when injecting queries in Program.cs I expected to register all Query classes with single line:

builder.Services.AddMediatR(Assembly.GetExecutingAssembly());

but it does not work, I had to define explicitly;

builder.Services.AddMediatR(typeof(GetAllProductsQuery));

GetAllProductsQuery.cs file in a class library, it's in the same solution.

I expect it to registered via Assembly.GetExecutingAssembly().

Why is it not working, and how can I avoid defining each query cqrs class explicitly?


Solution

  • Assembly.GetExecutingAssembly returns the assembly where the current code is being executed, so if it is not called from assembly (library) where your query classes are placed then it will not register those (in this case it should return assembly with the top-level statement, i.e. Program.cs).

    Try getting assembly from a class located in the class library containing the queries:

    builder.Services.AddMediatR(typeof(GetAllProductsQuery).Assembly);