Decorate a specific type of a generic IRequestHandler<T,K> mediator using autofac .net 6

Viewed 28

I use mediatr nuget package and autofac in an api .net 6.

I would like to decorate a specific command only of the IRequestHandler<T,K> of the Mediator, and not all the commands that I have.

For example, i have the IRequestHandler<UpdateWallet, AmountCalculation> And i would like to decorate only this command handler with a class AmountCalculationDecorator.

class AmountCalculationDecorator: IRequestHandler<UpdateWallet, AmountCalculation>
    {
        private readonly IRequestHandler<UpdateWallet, AmountCalculation> _decorated;

        public AmountCalculationDecorator(
            IRequestHandler<UpdateWallet, AmountCalculation> decorated)
        {
            _decorated = decorated;
        }

        public async Task<AmountCalculation> Handle(UpdateWallet request, CancellationToken cancellationToken)
        {
          // mpla mpla
        }
    }

Now i try to register this decorator in the autofac di.

public partial class ApplicationModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var thisAssembly = Assembly.GetExecutingAssembly();

            builder
                .RegisterMediatR(thisAssembly);

            builder
                .RegisterDecorator<AmountCalculationDecorator, IRequestHandler<UpdateWallet, AmountCalculation>>();
        }
    }

But i get

Circular component dependency detected:AmountCalculationDecorator.

How can achieve this implementation?

1 Answers

The problem is following: .RegisterMediatR(thisAssembly) automatically registeres all implementations of IRequestHandlers, including AmountCalculationDecorator. Then you register AmountCalculationDecorator as a decorator for IRequestHandler<UpdateWallet, AmountCalculation>, so it's a decorator for itself... hence the circular dependency.

You can see the RegisterMediatR method code here.

The easiest solution I can see is not to provide the assembly to RegisterMediatR, but to register the handlers by yourself and then you can fully controll, which implementations you want to register (e.g. by namespace or publicity). Or you can fully remove this nuget package and register MediatR by yourself

Related