Search code examples
.net-6.0mediatr

Could not load type 'MediatR.ServiceFactory'


I'm creating an Api and I am also using mediatR, I have created my commands, queries, handlers, but when I try to launch my Api I get this error message in my program class:

Could not load type 'MediatR.ServiceFactory' from assembly 'MediatR, Version=12.0.0.0, Culture=neutral, PublicKeyToken=bb9a41a5e8aaa7e2'.

I'm registering my mediatR in my program class like this:

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

I have installed the MediatR (latest version: 12.0.0) and the MediatR.Extensions.Microsoft.DependencyInjection (version: 11.0.0 ) because the latest version(11.1.0) at this moment is deprecated. enter image description here

I'm using .Net 6, any possible solution? thanks in advance.


Solution

  • The update to MediatR 12 comes with a Migration Guide here.

    To solve your issue, replace

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

    with

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

    If you have a handler from another (single) assembly, you can try this:

     services.AddMediatR(cfg=>cfg.RegisterServicesFromAssemblies(typeof(MyCoolThingInAnotherAssemblyRequestHandler).GetTypeInfo().Assembly));
    

    To use any of the above extension methods..you may need to add:

    using MediatR;
    

    From Migration guide

    Service registration through configuration object exclusively Service registration through IServiceCollection previously had overloads for various options. These are now consolidated into the single MediatrServiceConfiguration object. Overloads that passed through the assemblies to scan need to register using methods on this configuration object instead: