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

Viewed 21266

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

7 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.

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

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;

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

You have to change:

namespace App\Controller;

with:

namespace App\Controller\Api;

In my case it was an error in the controller name when I used the bin/console command :

bin/console make:controller APIController this command add automatically suffix -Controller to the file.

Then the controller created is called APIControllerController.

Next I made a copy/paste of Auth0 guide to create API nammed APIController.

In the end the file had the name APIControllerController.php and the class APIController: you just had to change the filename and remove the duplicate -Controller suffix.

Or - in general - verify the name of file controller and the class name ;)

I have just resolved this issue.
Turned out for me - I had miss typed __construct() as a private function, should be public

Related