简体   繁体   English

多个RabbitMQ交换和队列的DI配置

[英]DI configuration for multiple RabbitMQ exchanges and queues

I'm trying to configure DI for EventBusRabbitMQ implementation. 我正在尝试为EventBusRabbitMQ实现配置DI。 It works perfectly fine for a single exchange, queue.. 对于单个交换,队列,它工作得很好。

 services.AddSingleton<IEventBus, EventBusRabbitMQ>(serviceProvider =>
 {
     ...

     return new EventBusRabbitMQ(connection, "exchange_EX1", "queue_Q1",..);
 });

and in the application configuration 并在应用程序配置中

var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();

eventBus.Subscribe<FooEvent, FooEventHandler>;

I want to register multiple implementations with different configurations of EventBusRabbitMQ so i can pick and choose which exchange and queue to target when i resolve for IEventBus. 我想用EventBusRabbitMQ的不同配置注册多个实现,以便在我解决IEventBus时可以选择要选择的交换和队列。

What i don't want is to be explicit about the implementations since the only thing that differs is just the exchange and queue. 我所不希望的是明确实现,因为唯一不同的只是交换和队列。

services.AddSingleton<IEventBus, EventBusRabbitMQ_EX1_Q1>
services.AddSingleton<IEventBus, EventBusRabbitMQ_EX2_Q2>

what alternates do i have? 我有什么替代品?

I think the best solution given you have a finit set of implementation is to consider a solution like this: 我认为,如果您有一套有限的实现,最好的解决方案就是考虑这样的解决方案:

public interface  IEventBusRabbitMQ_EX1_Q1:IEventBus
{
}
public interface  IEventBusRabbitMQ_EX2_Q2:IEventBus
{
}

and then change your code to inject the right instance 然后更改您的代码以注入正确的实例

services.AddSingleton<IEventBusRabbitMQ_EX1_Q1, EventBusRabbitMQ_EX1_Q1>
services.AddSingleton< IEventBusRabbitMQ_EX2_Q2, EventBusRabbitMQ_EX2_Q2>

But there is another solution which is described here 但是这里描述另一种解决方案

basically is an enricher kind pattern like but I don't recommend it because it reduces the readability of the code. 基本上是一种更丰富的模式,但我不建议这样做,因为它会降低代码的可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM