Monolite
Monolite

Reputation: 111

Cannot autowire service

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('[email protected]');
        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?

Upvotes: 11

Views: 21982

Answers (1)

Sam
Sam

Reputation: 6620

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'

Upvotes: 37

Related Questions