如何将@request 注入服务? [英] How to inject the @request into a service?

查看:25
本文介绍了如何将@request 注入服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将@request 注入到我的任何服务中时,出现此异常:

When I try to inject the @request into any of my services, I get this exception:

ScopeWideningInjectionException:检测到范围扩大注入:定义service.navigation"引用服务请求"属于更窄的范围.一般来说,两者都比较安全将service.navigation"移动到请求"范围或依赖于通过注入容器本身并请求提供者模式每次需要时服务请求".在极少数特殊情况下但是这可能不是必需的,那么您可以将引用设置为strict=false 以消除此错误.

ScopeWideningInjectionException: Scope Widening Injection detected: The definition "service.navigation" references the service "request" which belongs to a narrower scope. Generally, it is safer to either move "service.navigation" to scope "request" or alternatively rely on the provider pattern by injecting the container itself, and requesting the service "request" each time it is needed. In rare, special cases however that might not be necessary, then you can set the reference to strict=false to get rid of this error.

最好的方法是什么?我应该尝试设置这个 strict=false 以及如何设置,或者我不应该注入请求服务,而是在每次调用我需要的函数时通过我的控制器将它传递给服务?

What is the best way to proceed? Should I try to set this strict=false and how, or should I NOT inject the request service, but rather pass it to the service through my controller each time I call functions I need?

其他可能性是注入内核并从那里获取它,但在我的服务中我只使用@router 和@request,所以注入整个内核是不合理的.

Other possibility would be to inject the kernel and take it from there, but in my service I am using only @router and @request, so injecting the whole kernel would be irrational.

推荐答案

我认为可能对官方文档所说的内容存在一些误解.在大多数情况下,您确实希望使用服务元素上的 scope="request" 属性直接注入请求.这使得范围扩大消失了.

I think there may have been some misunderstanding about what the official documentation says. In most cases you do want to inject the request directly with a scope="request" attribute on the service element. This makes the Scope Widening go away.

<service 
    id="zayso_core.openid.rpx" 
    class="ZaysoCoreBundleComponentOpenidRpx" public="true" scope="request">

或在yml

zayso_core.openid.rpx: 
    class: ZaysoCoreBundleComponentOpenidRpx
    public: true
    scope: request

只有在特定的特殊情况下,例如 Twig 扩展,您才需要注入容器.

It's only in specific special cases such as Twig extensions where you need to inject the container.

内核甚至没有在关于范围的页面中提到.注入内核比注入容器更糟糕(在概念上).

And kernel is not even mentioned in the page on scopes. Injecting the kernel is far worse (conceptually) than injecting a container.

更新:对于 S2.4 及更新版本,请使用下面@Blowski 的回答.

UPDATE: For S2.4 and newer, use @Blowski's answer below.

这篇关于如何将@request 注入服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆