如何解决Steeltoe 消息与 RabbitMQ - 侦听器和依赖注入问题
我正在使用 Steeltoe 在微服务之间通过 RabbitMQ 实现事件消息传递,但是当我注册我的侦听器服务并且它无法识别其他 DI 服务时遇到了问题。
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
无法注入侦听器服务,因为它未注册。我无法弄清楚为什么这不起作用。是因为我试图将 范围内的 服务注入到 singleton 服务中吗?
更新
我进行了一些测试并将 IMyService 从范围服务更改为单例服务使其工作。现在我需要弄清楚如何解决这个问题,因为在我的情况下,将 IMyService 注册为单例是没有意义的。
解决方法
此错误的原因是您无法从单例中使用范围服务。 Scoped 具有每个请求语义,这对于消息传递没有意义。也许你的意思是 AddTransient?这样可行。如果这对您不起作用,您能否详细说明为什么 MyService 不能只是暂时的?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。