rabbitmq 使用MassTransit将服务注入队列使用者

qq24tv8q  于 11个月前  发布在  RabbitMQ
关注(0)|答案(2)|浏览(151)

我有一个消费者,配置如下

.ConfigureServices((hostContext, services) =>
{
    services.AddMassTransit(cfg =>
    {
        cfg.AddConsumer <Consumers>();
        cfg.UsingRabbitMq((context, cfgss) =>
        {
            cfgss.Host(new Uri("rabbitmq://localhost/"), hostss =>
            {
                hostss.Username("guest");
                hostss.Password("guest");
            });

            cfgss.ReceiveEndpoint("Queue_Name", configureEndpoint =>
            {
                //configureEndpoint.ConfigureConsumer<Consumers>(context);
                configureEndpoint.Consumer<Consumers>();
            });

            cfgss.ConfigureEndpoints(context);
        });
    });
})

字符串
服务是在ContainerBuilder上使用Autofac创建的,EventService是应该注入到消费者中的服务

var host = new HostBuilder()
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureHostConfiguration(configHost => { configHost.SetBasePath(Directory.GetCurrentDirectory()); })
    .ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.AddJsonFile("appsettings.json", optional: false);
    })
    .ConfigureContainer<ContainerBuilder>(builder =>
    {
        builder.RegisterType<EventService>().As<IService>();
}


这就是消费者

public Consumers() { }
    
public Consumers(IService EventService)
{
    _eventsService = EventService;
}

public Task Consume(ConsumeContext<Msg> context)
{
    _eventsService.ProcessInternal(context.Message);
    return Task.CompletedTask;
}


每当接收到消息时,都会调用空构造函数,但_eventsService为null

brccelvz

brccelvz1#

使用ConfigureConsumer

cfgss.ReceiveEndpoint("Queue_Name", configureEndpoint =>
{
    configureEndpoint.ConfigureConsumer<Consumers>(context);
});

字符串
并完全移除空构造函数。

pkln4tw6

pkln4tw62#

我在这个帖子中找到了解决方案
Link
需要将消费者添加到配置和AddMassTransitHostedService
这是最终的工作配置:

services.AddMassTransit(cfg =>
{
    cfg.AddConsumer<Consumers>();
    cfg.UsingRabbitMq((context, cfgss) =>
    {
        cfgss.Host(new Uri("rabbitmq://localhost/"), hostss =>
        {
            hostss.Username("guest");
            hostss.Password("guest");
        });

        cfgss.ReceiveEndpoint("Queue_Name", configureEndpoint =>
        {
            configureEndpoint.ConfigureConsumer<Consumers>(context);
        });

        cfgss.ConfigureEndpoints(context);
    });
});
services.AddMassTransitHostedService();

字符串

相关问题