Rya*_*all 4 dependency-injection symfony
我正在尝试通过旨在替换 FOSRestBundle 中的服务之一的编译器传递注入令牌存储服务:
<?php
namespace App\Compiler;
use App\Event\Listener\RestParamConverter;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class RestParamConverterOverride implements CompilerPassInterface
{
/**
* You can modify the container here before it is dumped to PHP code.
*
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('fos_rest.converter.request_body');
$definition->setClass(RestParamConverter::class);
$definition->addArgument($container->getDefinition('security.token_storage'));
}
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,即使安全系统正确设置了 中的令牌TokenStorage,在我访问 的自定义服务中TokenStorage,$tokenStorage->getToken()似乎返回null. 在我尝试检索值之前,我已经调试了代码并确保身份验证正在运行。
我已经使用其他服务进行了测试,并且我看到了我注入的任何$definition->addArgument($container->getDefinition(SERVICE_HERE));. 这很奇怪,但在编译器传递中,它似乎创建了该服务的新实例,而不是使用共享服务。
在其他部分,服务注入工作正常——只是在这些编译器通道中没有。任何人都可以解释为什么会这样吗?
文档展示了如何注入对现有服务的引用,而不是创建服务的新实例:https : //symfony.com/doc/current/components/dependency_injection.html#basic-usage
具体来说,使用:
$definition->addArgument(new Reference('service_name'))
Run Code Online (Sandbox Code Playgroud)