使用 autofac .net 6 装饰特定类型的通用 IRequestHandler<T,K> 中介器

问题描述 投票:0回答:1

我在 api .net 6 中使用 mediatr nuget 包和 autofac。

我只想装饰中介者的 IRequestHandler 的特定命令,而不是我拥有的所有命令。

例如,我有 IRequestHandler 我只想用 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
        }
    }

现在我尝试在 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>>();
        }
    }

但我明白了

检测到循环组件依赖性:AmountCalculationDecorator。

如何实现这个实现?

c# asp.net-core .net-core autofac .net-6.0
1个回答
0
投票

问题如下:

.RegisterMediatR(thisAssembly)
自动注册
IRequestHandler
的所有实现,包括
AmountCalculationDecorator
。然后你将
AmountCalculationDecorator
注册为
IRequestHandler<UpdateWallet, AmountCalculation>
的装饰器,因此它本身就是一个装饰器......因此存在循环依赖。

您可以在

此处
查看RegisterMediatR方法代码。

我能看到的最简单的解决方案是不向 RegisterMediatR 提供程序集,而是自己注册处理程序,然后您可以完全控制要注册的实现(例如通过命名空间或公开)。或者你可以完全删除这个nuget包并自己注册MediatR

另一种选择: 您可能还想使用管道行为而不是装饰器。这是 MediatR 内置的 decorate 处理程序调用方法

© www.soinside.com 2019 - 2024. All rights reserved.