MassTransit 无法使用 IRequestClient - 依赖注入问题

MassTransit unable to use IRequestClient - dependency injection issue

在 Startup.ConfigureServices 我正在添加 MassTransit 配置

services.AddMassTransit(config =>
{
       config.SetKebabCaseEndpointNameFormatter();
       config.AddRequestClient<RegisterCarOwner>();
       config.AddBus(provider => Bus.Factory.CreateUsingRabbitMq();
});
  
services.AddMassTransitHostedService();

在处理程序中我使用此客户端发送消息

public class RegisterCarOwnerHandler : IRequestHandler<RegisterCarOwnerCommand, Unit>
{
    private readonly IRequestClient<RegisterCarOwner> _registerOwnerClient;
    public RegisterCarOwnerHandler(IRequestClient<RegisterCarOwner> registerOwnerClient)
    {
       _registerOwnerClient = registerOwnerClient
    }

    public async Task<Unit> Handle(RegisterCarOwnerCommand command, CancellationToken token)
    {
       ...
    }
}

System.AggregateException: '无法构建某些服务(在尝试激活 'xxxx.RegisterCarOwnerHandler ' 时验证服务描述符 'ServiceType: MediatR.IRequestHandler2[xxxx.RegisterCarOwnerCommand] Lifetime: Transient ImplementationType: xxxx.TestHandler': Unable to resolve service for type 'MassTransit.IRequestClient1[RegisterCarOwner.RegisterCarOwnerHandler]' 时出错。)'

更新:

public class Startup
{
    public Startup(IConfiguration configuration) { Configuration = configuration; }
    public IConfiguration Configuration { get; }
    
    public void ConfigureServices(IServiceCollection services)
    {
        ....        
        var rabbitMqConf = new RabbitMqConfiguration();
        this.Configuration.GetSection(RabbitMqConfiguration.SectionName).Bind(rabbitMqConf);

        services.AddMassTransit(x =>
        {
            x.AddRequestClient<RegisterCarOwner>();
            x.UsingRabbitMq((context, cfg) =>
            {
                cfg.SetKebabCaseEndpointNameFormatter();
                cfg.Host(new Uri(rabbitMqConf.ConnectionUrl), c => 
                {
                    c.Username(rabbitMqConf.Username);
                    c.Password(rabbitMqConf.Password);
                });
                cfg.ConfigureEndpoints(context);
            });
        });
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ....
        app.UseRouting();
        app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
    }
}   

IRequestClient<T> 有作用域,而您正试图在没有作用域的情况下解析它。

另外,你的总线配置严重过时,改:

config.AddBus(provider => Bus.Factory.CreateUsingRabbitMq();

支持的语法:

config.UsingRabbitMq((context, cfg) => {});