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

查看:143
本文介绍了如何将@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 ,以及如何或不应该注入请求服务,而是每次调用函数I通过我的控制器将其传递给服务需要?

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="Zayso\CoreBundle\Component\OpenidRpx" public="true" scope="request">

yml

zayso_core.openid.rpx: 
    class: Zayso\CoreBundle\Component\OpenidRpx
    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天全站免登陆