0
votes

I am making simple application with Symfony. I have services configured here

services:
app.service.comments_service:
    class: AppBundle\Service\CommentsService
    autowire: true

app.service.projects_service:
    class: AppBundle\Service\ProjectService
    autowire: true
app.service.files_service:
        class: AppBundle\Service\FilesService
        autowire: true
app.service.users_service:
            class: AppBundle\Service\UserService
            autowire: true

My services use repositories (comments service uses comments repository for example) and here is the constructor of CommentsService

Properties

    private $entityManager;
    private $session;
    private $manager;
    private $commentsRepository;

Constructor:

public function __construct(
    EntityManagerInterface $entityManager,
    Session $session,
    ManagerRegistry $manager,CommentsRepository $commentsRepository)
{
    $this->entityManager = $entityManager;
    $this->session = $session;
    $this->manager = $manager;
    $this->commentsRepository = $commentsRepository;
}

When I try to run my application I get this error

PHP Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\AutowiringFailedException: Cannot autowire service "AppBundle\Repository\CommentsRepository": argument "$em" of method "Doctr ine\ORM\EntityRepository::__construct()" must have a type-hint or be given a value explicitly. Cannot autowire service "app.service.comments_service": argument "$commentsRepository" of method "AppBundle\Service\CommentsService::__construct()" references class "AppBundle\Repository\CommentsRepos itory" but no such service exists. in C:\xampp\htdocs\WINbetTaskManager\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Compiler\AutowirePass.php:285

Any ideas how I could fix this?

1
Autowire has many limitations and this is one of them. You need to use a factory to create a repository (basically EntityManager::getRepository(Comment::class) You can search for the details and just define the repository services individually. I think autowire should then pick them up.Cerad
@Cerad I believe it should be an answer, not comment. Upvoted though:)svgrafov
@svgrafov Thanks but while I do know how repository services work I have not done much with autowire itself so I don't really know if other problems will crop up. In other words, this is more of a guess than an answer.Cerad

1 Answers

1
votes

So I did a bit of experimenting and this seems to work:

// services.yml
AppBundle\Repository\CommentsRepository:
    factory: 'doctrine.orm.entity_manager:getRepository'
    arguments: ['AppBundle\Entity\Comments']

That should give autowire enough information to inject the repository.