Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Misleading exception message when injecting ContainerInterface into a service without implementing the ServiceSubscriberInterface #36563

Closed
@keichinger

Description

@keichinger

Symfony version(s) affected: 4.4.7

Description
When you're having a service that receives a ContainerInterface but forgot to implement the ServiceSubscriberInterface, you'll get an exception message saying:

„The "App\MyService" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.”

How to reproduce

<?php declare(strict_types=1);

namespace App\AwesomeThings;

use App\MyService;
use Psr\Container\ContainerInterface;

class AwesomeService
{
    private ContainerInterface $container;

    public function __construct (ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function doSomething () : void
    {
        // The exception happens here!
        //    - „The "App\MyService" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.”
        $myService = $this->container->get(MyService::class);
        // …
    }

    /**
     * @inheritdoc
     */
    public static function getSubscribedServices () : array
    {
        return [
            MyService::class,
        ];
    }
}

class MyService {}

To fix the actual underlying exception here, we simply have to implement the forgotten ServiceSubscriberInterface:

<?php declare(strict_types=1);

namespace App\AwesomeThings;

use App\MyService;
use Psr\Container\ContainerInterface;

class AwesomeService implements ServiceSubscriberInterface
{
    private ContainerInterface $container;

    public function __construct (ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function doSomething () : void
    {
        $myService = $this->container->get(MyService::class);
        // …
    }

    /**
     * @inheritdoc
     */
    public static function getSubscribedServices () : array
    {
        return [
            MyService::class,
        ];
    }
}

class MyService {}

Possible Solution
Make the exception more context-sensitive/clear to this actual use-case

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions