Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

references class "Doctrine\ODM\MongoDB\UnitOfWork" but no such service exists

I'm currently using Symfony 4 with Doctrine MongoDB Bundle, following the instruction from this link: DoctrineMongoDBBundle. So, I have a UserDocument:

src/Document/UserDocument.php

/** @MongoDB\Document(collection="user", repositoryClass="App\Repository\UserRepository") */
class UserDocument
{

    /**
     * @MongoDB\Id
     * @var ObjectId
     */
    private $id;

    /**
     * @MongoDB\Field(type="string", name="first_name")
     * @var string
     */
    private $firstName;

    /**
     * @MongoDB\Field(type="string", name="middle_name")
     * @var string
     */
    private $middleName;

    /**
     * @MongoDB\Field(type="string", name="last_name")
     * @var string
         */
        private $lastName;
    }

src/Repository/UserRepository.php

use Doctrine\ODM\MongoDB\DocumentRepository;
class UserRepository extends DocumentRepository
{

}

src/Controller/Content.php

class Content extends Controller

{

    /**
     * @Route("/content", name="content")
     * @param UserRepository $user
     * @return Response
     */
    public function index(UserRepository $user)
    {
        $user->findAll();
        return new Response();
    }


}

So, after running the content page, I got the following error:

Cannot autowire service "App\Repository\UserRepository": argument "$uow" of method "__construct()" references class "Doctrine\ODM\MongoDB\UnitOfWork" but no such service exists.

The DocumentRepository constructor looks like this:

public function __construct(DocumentManager $dm, UnitOfWork $uow, ClassMetadata $classMetadata)
    {
        parent::__construct($dm, $uow, $classMetadata);
    }
like image 267
Hope Avatar asked Sep 29 '25 09:09

Hope


2 Answers

Repository shouldn't be Services, but if you want to keep it that way, just Autowire the DocumentManager and get the uow and classmetdata from the Document Manager.

UnitOfWork and ClassMetadata can't be autowired

Do something like that in your UserRepository, it should work.

public function __construct(DocumentManager $dm)
{
    $uow = $dm->getUnitOfWork();
    $classMetaData = $dm->getClassMetadata(User::class);
    parent::__construct($dm, $uow, $classMetaData);
}
like image 157
Etshy Avatar answered Oct 02 '25 04:10

Etshy


Make sure to exclude your repository class from autowiring. Example here: https://symfony.com/doc/current/service_container/3.3-di-changes.html

In case you want your repository class as a service you should do it using a factory service.

like image 22
Iwan Wijaya Avatar answered Oct 02 '25 05:10

Iwan Wijaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!