Cannot autowire service

我是研究僧i 提交于 2019-12-23 12:17:36

问题


I am trying to implement UserManager from FOSUserBundle (Symfony3.4).

Service/Register.php

<?php

namespace AppBundle\Service;

use FOS\UserBundle\Model\UserManager;


class Register
{
    private $userManager;

    public function __construct(UserManager $userManager)
    {
        $this->userManager = $userManager;
    }

    public function register() {
        $user = $this->userManager->findUserByUsernameOrEmail('aaa@gmail.clom');
        if($user){
            return false;
        }
        return true;
    }
}

When I try call this method I get:

Cannot autowire service "AppBundle\Service\Register": argument "$userManager" of method "__construct()" references class "FOS\UserBundle\Model\UserManager" but no such service exists. You should maybe alias this class to the existing "fos_user.user_manager.default" service.

What should I do now?


回答1:


I had a similar problem (in Symfony 4, but the principles should apply to 3.4) with a different service and managed to find the answer on the Symfony doc page Defining Services Dependencies Automatically (Autowiring).

Here's an extract from that page:

The main way to configure autowiring is to create a service whose id exactly matches its class. In the previous example, the service's id is AppBundle\Util\Rot13Transformer, which allows us to autowire this type automatically.

This can also be accomplished using an alias.

You need an alias because the service ID doesn't match the classname. So do this:

# app/config/services.yml
services:
    # ...

    # the `fos_user.user_manager.default` service will be injected when
    # a `FOS\UserBundle\Model\UserManager` type-hint is detected
    FOS\UserBundle\Model\UserManager: '@fos_user.user_manager.default'


来源:https://stackoverflow.com/questions/49307819/cannot-autowire-service

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