无法在TYPO3 9.5控制器中注入外部Repository问题求助
解决TYPO3 9.5跨插件Repository注入为null的问题
在TYPO3 9.5里跨扩展注入Repository遇到实例为null的问题,我之前也碰到过类似情况,咱们一步步来排查解决:
1. 修复注入方法的注解错误
你代码里的@param注解漏写了变量名,这会导致Extbase的依赖注入解析器无法正确识别依赖,赶紧补上:
/** * @var \Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository */ protected $optionRecordRepository = null; /** * @param \Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository $optionRecordRepository */ public function injectOptionRecordRepository(\Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository $optionRecordRepository) { $this->optionRecordRepository = $optionRecordRepository; }
2. 确保目标Repository被注册为公开服务
TYPO3 9.5默认会自动注册扩展Classes目录下的类为服务,但跨扩展调用时,目标服务需要设置为公开(public)。你需要在目标扩展ajaxselectlist的Configuration/Services.yaml中添加或修改配置:
services: Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository: public: true arguments: - '@TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager'
如果该文件不存在,直接创建即可。配置完成后,务必清除TYPO3的系统缓存(尤其是配置缓存)。
3. 备用方案:使用ObjectManager获取实例
如果上面的方法暂时未生效,你可以用ObjectManager作为临时解决方案,它能绕过自动注入的限制直接获取Repository实例:
首先注入ObjectManager:
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface; /** * @var ObjectManagerInterface */ protected $objectManager = null; /** * @param ObjectManagerInterface $objectManager */ public function injectObjectManager(ObjectManagerInterface $objectManager) { $this->objectManager = $objectManager; }
然后在动作函数中获取Repository并调用方法:
$optionRecordRepository = $this->objectManager->get(\Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository::class); $standorts = $optionRecordRepository->findAll(); $this->view->assign('standorts', $standorts);
4. 最后检查两个关键细节
- 确认目标扩展的
composer.json中PSR-4自动加载配置正确,示例如下:"autoload": { "psr-4": { "Sebkln\\Ajaxselectlist\\": "Classes/" } } - 彻底清除TYPO3缓存:进入后台「维护」→「清除缓存」,选择「全部缓存」,避免旧的DI配置干扰新设置。
按这个流程操作,应该就能解决注入实例为null的问题了。
内容的提问来源于stack exchange,提问作者Lorenz Karow
相关产品推荐
相关产品推荐

