我想在postFlush
服务的Proposals
方法中使用当前用户,因此我刚刚添加了SecurityContextInterface $securityContext
作为__construct
方法的参数,作为Proposals
服务类的属性:
use Symfony\Component\Security\Core\SecurityContextInterface;
/**
* @DI\Service("pro.proposals")
* @DI\Tag("doctrine.event_listener", attributes = {"event": "onFlush", "lazy": true})
* @DI\Tag("doctrine.event_listener", attributes = {"event": "postFlush", "lazy": true})
*/
class Proposals
{
private $doctrine;
private $translator;
private $templating;
private $notifications;
private $proposalsWithTypeChanged;
private $securityContext;
/**
* @DI\InjectParams({"notifications" = @DI\Inject("pro.notifications")})
*/
function __construct(Registry $doctrine, TranslatorInterface $translator, Notifications $notifications, Templating $templating, SecurityContextInterface $securityContext)
{
$this->doctrine = $doctrine;
$this->translator = $translator;
$this->templating = $templating;
$this->notifications = $notifications;
$this->securityContext = $securityContext;
}
但是这给了我这个错误:
ServiceNotFoundException:服务“pro.proposals”依赖于不存在的服务“security_context”。
我也尝试按this post的建议传递整个容器,但都不起作用。有什么建议吗?
答案 0 :(得分:0)
替换
/**
* @DI\InjectParams({"notifications" = @DI\Inject("pro.notifications")})
*/
与
/**
* @DI\InjectParams( {
* "notifications" = @DI\Inject("pro.notifications"),
* "securityContext" = @DI\Inject("security.context")
* } )
*/
我认为DIExtraBundle试图根据参数的名称来猜测服务名称。您必须明确指定服务ID。
如果您的安全上下文依赖于学说,您仍然可以按照其他帖子中的说明注入容器,例如:
/**
* @DI\Service("pro.proposals")
*/
class Test {
/**
* @var SecurityContextInterface
*/
protected $securityContext;
/**
* @DI\InjectParams({"container" = @DI\Inject("service_container")})
*/
function __construct( ContainerInterface $container ) {
$this->securityContext = $container->get( 'security.context' );
}
}