How to inject the @request into a service?

后端 未结 9 2247
Happy的楠姐
Happy的楠姐 2020-12-01 05:53

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

ScopeWideningInjectionException: Scope Widening Injection detected:

相关标签:
9条回答
  • 2020-12-01 06:43

    If you can't use RequestStack directly, you could create a factory service that returns the current request using RequestStack.

    # services.yml
    app.request:
        class: Symfony\Component\HttpFoundation\RequestStack
        factory: [ @request_stack, getCurrentRequest ]
    

    Then you can access the current request using the app.request service.

    0 讨论(0)
  • 2020-12-01 06:50

    another way to inject currentRequest directly:

    setter injection:

    calls:
         - ['setRequest', ['@=service("request_stack").getCurrentRequest()']]
    

    or constrauctor injection:

    arguments:
         $request: '@=service("request_stack").getCurrentRequest()'
    
    0 讨论(0)
  • 2020-12-01 06:51

    As @simshaun states its best practice to place your service in the request scope. This makes the purpose of the service quite clear.

    Note that this will make your service unavailable in other scopes such as the command line. However if your service relies upon the request, you should not be using it on the command line anyway (because there is no request available on the command line.

    0 讨论(0)
提交回复
热议问题