Adding MediatR service
Asked Answered
P

1

22

I want to add MediatR to my services.

Here is the code:

public class Program
{
   public static async Task Main(string[] args)
   {
      var builder = WebApplication.CreateBuilder(args);
      builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
   }
   // rest of codes ...
}

Here is the Error:

Error CS1503 Argument 2: cannot convert from 'System.Reflection.Assembly' to 'System.Action<Microsoft.Extensions.DependencyInjection.MediatRServiceConfiguration>'

Pekoe answered 4/3, 2023 at 13:35 Comment(0)
D
72

If you are using [email protected] you can use this:

builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

If you still want to use your version of code, then you should install MediatR.Extensions.Microsoft.DependencyInjection package but you might need to downgrade MediatR version to 11

Dilantin answered 4/3, 2023 at 14:39 Comment(4)
I ran into the same error when running the following two lines: builder.Services.AddMediatR(typeof(CreateCustomerCommandHandler).GetTypeInfo().Assembly); builder.Services.AddMediatR(typeof(CreateUserCommandHandler).GetTypeInfo().Assembly); I'm running MediatR version 12 Both of the above commands are in the same project. Will the code you posted infer which handler is being called or do I need to create multiple calls to .AddMediatR? I'm new to MediatR so please let me know if this is a separate issue.Inlet
@Inlet At version 12, there is only one AddMediatR method signature which takes an Action as a parameter. So passing assemblies directly as parameters is not valid. If your handlers are in different assemblies, then you can call cfg => cfg.RegisterServicesFromAssemblies(assembly1, assembly2...) instead of multiple AddMediatR call. This way MediatR can route the command/query to the related handler. If handlers are in the same assembly, then you should call it with a single assembly.Dilantin
That makes sense and I will try the first part where you put in multiple assemblies to avoid multiple AddMediatR calls where possible. Thank you!Inlet
Installing 'MediatR.Extensions.Microsoft.DependencyInjection' fixed the issueAmbrosine

© 2022 - 2024 — McMap. All rights reserved.