Streamlining MediatR Migration from Version 12.0 to 12.1

EduardEduard
2 min read

A few months ago, I worked on the task of migrating project services from MediatR version 12.0 to 12.1. I will not explain in detail what this fairly popular library is used for, nor will I talk about its advantages and disadvantages. Here, I just want to share my findings during the migration process. Perhaps they will help save your time and reduce the amount of code you need to write.

In the project, we widely use IRequestPreProcessor and IRequestPostProcessor, provided out of the box. They allow us to flexibly add, extend, and, if necessary, remove functionality in our Pipeline requests without any issues.

As mentioned in the author's article about the release of the new version MediatR 12.1, all automatic scanning of behaviors, stream behaviors, and pre/post processors were removed, allowing dependencies to be registered explicitly in the required order.

In my case, the order of registration did not matter much; however, the number of classes that I needed to register explicitly was enormous. The prospect looked grim, so I decided to explore the inner workings of the library for possible workarounds.

As it turned out, in the settings class MediatRServiceConfiguration, there is a flag AutoRegisterRequestProcessors, which can bring back the automatic scanning of pre/post processors. This, of course, is not mentioned in the official migration guide. If you need proof of my words, you can verify it by following this link to the library's source code.

The final result looks something like this:

public static IServiceCollection AddServices(this IServiceCollection services)
{
    services
        .AddMediatR(config =>
        {
            config.AutoRegisterRequestProcessors = true;
            config.RegisterServicesFromAssemblyContaining<IApplicationAssemblyMarker>();
            config.AddOpenBehavior(typeof(ValidationBehavior<,>));
            config.AddOpenBehavior(typeof(RequestPreProcessorBehavior<,>));
            config.AddOpenBehavior(typeof(RequestPostProcessorBehavior<,>));
        });

    return services;
}

However, despite the presence of the AutoRegisterRequestProcessors flag, it is still necessary to explicitly add pre/post processor behaviors; otherwise, the magic of automatic registration will not happen.

0
Subscribe to my newsletter

Read articles from Eduard directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Eduard
Eduard