如何将RabbitMqBundle生产者注入Symfony自定义服务?
解决RabbitMqBundle生产者注入自定义服务的问题
我来帮你搞定这个依赖注入的问题!从你的代码来看,首先得把构造函数里的赋值补全,然后确保Symfony能正确识别并注入对应的RabbitMQ生产者服务。
第一步:修正你的服务类代码
首先把构造函数里的$positionProducer赋值完成,直接把注入的$producer赋值给它就行:
namespace App\Service; use Carbon\Carbon; use Doctrine\ORM\EntityManagerInterface; use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface; class RatingPositionRecalculateService { protected $entityManager; protected $positionProducer; public function __construct(EntityManagerInterface $entityManager, ProducerInterface $producer) { $this->entityManager = $entityManager; // 补全生产者实例的赋值 $this->positionProducer = $producer; } // 可以添加一个使用生产者的示例方法 public function sendPositionUpdate($data) { $this->positionProducer->publish(json_encode($data)); } }
第二步:配置依赖注入(关键环节)
RabbitMqBundle会为你配置的每个生产者生成对应的服务,服务ID格式为old_sound_rabbit_mq.你的生产者名称_producer(比如你配置的生产者叫position,服务ID就是old_sound_rabbit_mq.position_producer)。你需要告诉Symfony该注入哪个具体实例:
方式1:显式配置服务(适用于关闭自动配置的场景)
在config/services.yaml里手动配置你的服务,指定注入的生产者:
services: App\Service\RatingPositionRecalculateService: arguments: $entityManager: '@doctrine.orm.entity_manager' $producer: '@old_sound_rabbit_mq.position_producer' # 替换成你的生产者实际服务ID
方式2:自动配置+绑定(更简洁的方式)
如果你的Symfony项目默认开启了自动配置(通常是开启状态),可以在services.yaml里绑定ProducerInterface到目标生产者服务,Symfony会自动完成注入:
services: _defaults: autowire: true autoconfigure: true public: false # 绑定ProducerInterface到指定的生产者服务 OldSound\RabbitMqBundle\RabbitMq\ProducerInterface: '@old_sound_rabbit_mq.position_producer' App\Service\RatingPositionRecalculateService: autowire: true # 开启自动注入依赖
常见问题排查
- 确认你的RabbitMQ生产者在
config/packages/old_sound_rabbit_mq.yaml里已正确配置,示例:old_sound_rabbit_mq: producers: position: connection: default exchange_options: { name: 'position_exchange', type: direct } - 检查服务ID是否正确:运行
bin/console debug:container | grep producer可以列出所有RabbitMQ生产者服务,找到你需要的那个ID。 - 确保自动配置未被禁用:在
services.yaml的_defaults区块确认autowire: true和autoconfigure: true已开启。
内容的提问来源于stack exchange,提问作者nass
相关产品推荐
相关产品推荐

