mediatr

How to add mediatr in .NET 6?


In .NET Core, we can add it in ConfigureServices method

services.AddMediatR(typeof(Startup));

But in .NET 6, there is only Program.cs. How to add mediatr in .NET 6?

Tried with this code but got build error

enter image description here


Solution

  • Before MediatR 12.0.0

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

    Since MediatR 12.0.0

        services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
    

    Edit (Explanation): The AddMediatR extension method needs an assembly to scan so it can register all the handlers and mediator types. In previous versions of dotnet we used the typeof(Startup) to point to the assembly of our asp project. We can always do the same thing instead of getting the executing assembly by creating an interface in our asp project, which can also be helpful at testing. Just create an empty interface with a meaningful name, for example something like IProjectNameMarker and then you can use typeof(IProjectNameMarker).