Symfony 3.3 services autoconfiguration

限于喜欢 提交于 2020-01-22 20:08:02

问题


I'm trying migrate to symfony 3.3 and use new feature autowire/autoconfigure services:

So in services.yml i have:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    # makes classes in src/AppBundle available to be used as services
    AppBundle\:
        resource: '../../src/AppBundle/*'
        # you can exclude directories or files
        # but if a service is unused, it's removed anyway
        exclude: '../../src/AppBundle/{Entity,Controller,DQL,Form/DataTransformer,Repository}'

i declare my twig extension as:

AppBundle\Twig\ImageExtension:
      arguments:
          $env: "%kernel.environment%"

and constructor for this service:

public function __construct(TokenStorage $token, UserRepository $userRepository, RedisCacheService $cache, string $env)
{
    $this->env = $env;
    $this->user = $token->getToken() ? $token->getToken()->getUser() : false;
    $this->userRepository = $userRepository;
    $this->cache = $cache;
}

seems that all is ok, but i'm getting this error:

(1/1) AutowiringFailedException
Cannot autowire service "AppBundle\Twig\ImageExtension": argument "$env" of method "__construct()" must have a type-hint or be given a value explicitly.

and have no idea how to fix it.


回答1:


I had same error message, but caused by different bug. Maybe somebody will find this useful.

My initial config in service.yml was:

app.my_service:
    class: 'AppBundle\Service\MyService'
    arguments:
        $foobar: 'some value for foobar'
    public: true

And I was getting this error:

Cannot autowire service "AppBundle\Service\MyService": argument "$foobar" of method "__construct()" must have a type-hint or be given a value explicitly.

Then few hours later I found the solution:

AppBundle\Service\MyService:
    arguments:
        $foobar: 'some value for foobar'

app.my_service:
    alias: AppBundle\Service\MyService
    public: true



回答2:


So problem was in case that i was trying to use services.yml from AppBundle, if i understand right, old style of importing services from bundles doesn't work with autowiring/autoconfiguring because we need to rewrite load() method from AppExtension to use type hints. So i've replaced all my services to app/config/services.yml and it helps me.



来源:https://stackoverflow.com/questions/44616346/symfony-3-3-services-autoconfiguration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!