服务\ "AppBundle\Service\Report\Generation\ACN"找不到:即使它存在于应用的容器中,容器内部



我正在尝试从容器

获得服务
if($responseType == 'json') {
$generator = $this->container->get('AppBundle\Service\Report\Generation\ACN');

我将它设置为public

AppBundleServiceReportGenerationACN:
public: true

但是没有找到服务,我错过了什么吗?

你不应该直接使用容器。只要使用DI,它就会自动注入所有需要的东西,比如:

use AppBundleServiceReportGenerationACN;
class MyController extends AbstractController 
{
public function myMethod(ACN $acnGenerator): Response
{
$acnGenerator->whatever();
return new Response('done');
}
}

或者当你需要在许多方法中使用Generator而不想随时注入它时,你可以使用(Symfony 4):

use AppBundleServiceReportGenerationACN;
class MyController extends AbstractController 
{
public static function getSubscribedServices()
{
return array_merge(parent::getSubscribedServices(), [
ACN::class,
]);
}
public function myMethod(): Response
{
$this->container->get(ACN::class)->whatever();
return new Response('done');
}
}

或者,在较新的Symfony版本中,带有Attributes:

use SymfonyContractsServiceAttributeRequired;
use AppBundleServiceReportGenerationACN;
class MyController extends AbstractController
{
#[Required]
public ACN $acnGenerator;
public function myMethod(): Response
{
$this->acnGenerator->whatever();
return new Response('ok');
}
}

最新更新