Home > Blockchain >  MediatR registiring query class in diffirent class library not working
MediatR registiring query class in diffirent class library not working

Time:10-02

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 its not working I had to define explicitly;

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

GetAllProductsQuery.cs file in a class library, its in same solution

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

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

CodePudding user response:

Assembly.GetExecutingAssembly returns the assembly where the current code is being executed on, so if it is not called from assembly (library) where your query classes are placed then it will not register those.

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

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

CodePudding user response:

Your problem can be solved by such way

var stateAssembly = AppDomain.CurrentDomain.Load("State");
var queriesAssembly = AppDomain.CurrentDomain.Load("Queries");
services.AddMediatR(stateAssembly, queriesAssembly);

Where "State" and "Queries" as example from my code is same name as class library where your query classes exists

  • Related