Search code examples
c#asp.net-core.net-coremediatr

get type from library assembly


I want to create a .NET Core REST API with MediatR. My projects are

  • API project
  • Application project containing the commands, queries and pipeline behaviours

To setup the dependency injection I have to call the

services.AddMediatR(typeof(Startup));

in the ConfigureServices method of the Startup.cs (API project). My commands and queries come from a different assembly (Application) so I have to pass in the library assembly instead of Startup. Please see the answer from this post

Why doesn't Mediatr resolve method when entites are in different projects?

My code should look like

services.AddMediatR(typeof(ApplicationAssembly));

but I can't just pass in "Application". What needs to get passed in, when commands and queries come from a library project?


I solved it by passing in a class from that library

services.AddMediatR(typeof(Application.Queries.GetUsersQuery));

I think this is a really bad approach because when this class gets moved or deleted, the API projects needs to get fixed too.

So any better solutions are highly appreciated


Solution

  • If i understood correctly, you need to pass type information from the assembly, not specific class types.

    On the github project of the extensions you will see this line in the examples

    ..... or with an assembly:

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

    Which is what you are looking for i think.
    In your case the code will look something like this:

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

    If you want to be fully independant of the type then you can use something like this

    services.AddMediatR(AppDomain.Current.GetAssemblies());  
    

    This will scan all assemblies loaded in the app domain.