Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller has no container set, did you forget to define it as a service subscriber

I'm trying to refactor some controllers in Symfony 5 server, but suddenly I'm unable to change or create controllers because of the following error:

'App\Controller{{ControllerName}}' has no container set, did you forget to define it as a service subscriber?

This is the controller:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Shiftsummary;
use App\Entity\Station;
use App\Entity\Shift;
use App\Entity\Line;
use \Datetime;

class StartStationController extends AbstractController {
    /**
     * @Route("/start", name="StartStation")
     */

    public function route(Request $request)
    {
      ...
    }  }

This is the content of service.yaml

services:
    _defaults:
        autowire: true  
        autoconfigure: true 

    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

The controllers are inside the src/controller/ folder

enter image description here

like image 748
RicardoAgra Avatar asked Apr 06 '20 12:04

RicardoAgra


4 Answers

The issue had to do with the cached files, deleting /var/cache made the error not occur.

Thanks go to Cerad for point this out.

like image 132
RicardoAgra Avatar answered Nov 07 '22 03:11

RicardoAgra


this is just it, your controller did not have container injected. However, framework expects it to be done if your controller inherits from AbstractController.

in ControllerResolver.php: enter image description here

TLDR; What you need is to inject it.

In your services.yaml, add the following setter call

![enter image description here

like image 44
Sergey Grechin Avatar answered Nov 07 '22 05:11

Sergey Grechin


I have to add that if you set the wrong namespace, you get this error too:

// src/Controller/Api/ProductController.php

namespace App\Controller;

class ProductController extends AbstractController {}

namespace must follow folders structure.

namespace App\Controller\Api;
like image 28
Alexis Vandepitte Avatar answered Nov 07 '22 05:11

Alexis Vandepitte


In my case, the class had just a different name than the file.

like image 21
Martin Lévai Avatar answered Nov 07 '22 04:11

Martin Lévai