【问题标题】:Steeltoe Messaging with RabbitMQ - Listener and Dependency Injection issue使用 RabbitMQ 的 Steeltoe 消息传递 - 侦听器和依赖注入问题
【发布时间】:2021-04-11 22:47:42
【问题描述】:

我正在使用 Steeltoe 在微服务之间通过 RabbitMQ 实现事件消息传递,但是当我注册我的 Listener 服务并且它无法识别其他 DI 服务时遇到问题。

在我的Startup.cs 文件中,我的服务注册如下:

public void ConfigureServices(IServiceCollection servcies)
{
    ...

    // Add my custom service as a scoped service
    services.AddScoped<IMyService>(provider => new MyService());

    var rabbitSection = configuration.GetSection(RabbitOptions.PREFIX);
    services.Configure<RabbitOptions>(rabbitSection);

    services.AddRabbitServices();
    services.AddRabbitAdmin();
    services.AddRabbitTemplate();

    // Add Rabbit Listener Service
    services.AddSingleton<MyRabbitListenerService>();
    services.AddRabbitListeners<MyRabbitListenerService>();

    ...
}

...然后在我的MyRabbitListenerService.cs 班级:

public class MyRabbitListenerService
{
    private readonly IMyService _myService;

    public MyRabbitListenerService(IMyService myService)
    {
        _myService = myService;
    }

    [RabbitListener("MyQueue")]
    public async Task MessageListener(byte[] message)
    {
        // Do stuff ...
    }
}

当我运行它时,我收到一条错误消息,指出 IMyService 由于未注册,因此无法注入到侦听器服务中。我无法弄清楚为什么这不起作用。是因为我试图将 scoped 服务注入 singleton 服务吗?

更新

我进行了一些测试并将 IMyService 从范围服务更改为单例使其工作。现在我需要弄清楚如何解决这个问题,因为在我的情况下,将 IMyService 注册为单例是没有意义的。

【问题讨论】:

    标签: c# .net-core rabbitmq microservices steeltoe


    【解决方案1】:

    此错误的原因是您无法从单例中使用作用域服务。 Scoped 具有每个请求的语义,这对于消息传递没有意义。也许您的意思是 AddTransient?这样可行。如果这对您不起作用,您能否详细说明为什么 MyService 不能只是暂时的?

    【讨论】:

    • 我可以将 MyService 设为瞬态,但在我的情况下,此服务是与外部 Web Api 交互的方法的包装器。我想这会更适合Scoped(甚至可能是Singleton)。
    • Scoped 是每个 HttpWebRequest,用于通过 ANC 管道传入的请求,您的应用程序在其中充当服务器。 RabbitListener 是一个长时间运行的进程,它监听传入的消息,但这些不是 HttpWebRequests。如果您希望每个 rabbitMQ 消息都有一个新对象,那么正确的类型应该是瞬态的。在您的情况下,如果您使用的是 httpClient,那么单例将是正确的类型。
    猜你喜欢
    • 2018-05-03
    • 2014-07-09
    • 1970-01-01
    • 2019-06-17
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多