Search code examples
symfonydependency-injection

Symfony: Explicit define Container in Service


After updating I have this deprecation:

Since symfony/dependency-injection 5.1: The "Symfony\Component\DependencyInjection\ContainerInterface" autowiring alias is deprecated. Define it explicitly in your app if you want to keep using it. It is being referenced by the "App\Service\ImportService" service.

Here is my ImportService:

<?php

namespace App\Service;

use Symfony\Component\DependencyInjection\ContainerInterface;

class ImportService
{
    private $doctrine;
    private $em;

    public function __construct(ContainerInterface $container)
    {
        $this->doctrine = $container->get('doctrine'); //needed for database queries
        $this->em = $this->doctrine->getManager(); //needed for database queries
    }

    /** more methods here **/

}

So how exactly do I make it explicit? I googled a bit and I think that I have to add it to my services.yml file somehow. But I am unsure how + do I have to do it for every Service class?


Solution

  • I just created a new 5.1 app and did not get the deprecation. Symfony is really discouraging the injection of the global container. So I am not surprised it is being deprecated.

    To fix the message, all you need to do is to explicitly define the ContainerInterface alias:

    # services.yml or yaml 
    services:
        Symfony\Component\DependencyInjection\ContainerInterface: '@service_container'
    

    That should do the trick. However, since you appear to be moving to 5.1 then you should start refactoring your code and only inject what a particular class needs. It is not mandatory but will save you from problems down the line:

    class ImportService
    {
        private $em;
    
        public function __construct(EntityManagerInterface $em)
        {
            $this->em = $em
        }