Closed
Description
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