为什么 symfony 容器有服务重复项?

Why does symfony container has service duplicates?

我想将 class App\Service\SomeService 注册为服务。

这是我的 services.yaml:

services:
    _defaults:
        autowire: false
        autoconfigure: true
        public: true
    App\:
        resource: '../src/*'
        exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']
    someservice:
        class: App\Service\SomeService

现在我运行debug:container someservice:

Information for Service "someservice"
=====================================

 ---------------- ------------------------- 
  Option           Value                    
 ---------------- ------------------------- 
  Service ID       someservice              
  Class            App\Service\SomeService  
  Tags             -                        
  Public           yes                      
  Synthetic        no                       
  Lazy             no                       
  Shared           yes                      
  Abstract         no                       
  Autowired        no                       
  Autoconfigured   yes                      
 ---------------- ------------------------- 

而且,当我 运行 debug:container App\Service\SomeService:

Information for Service "App\Service\SomeService"
=================================================

 ---------------- ------------------------- 
  Option           Value                    
 ---------------- ------------------------- 
  Service ID       App\Service\SomeService  
  Class            App\Service\SomeService  
  Tags             -                        
  Public           yes                      
  Synthetic        no                       
  Lazy             no                       
  Shared           yes                      
  Abstract         no                       
  Autowired        no                       
  Autoconfigured   yes                      
 ---------------- ------------------------- 

原来我有另一个服务指向同一个 class:

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Service\SomeService;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     * @return Response
     */
    public function index()
    {
        var_dump($this->get('someservice') === $this->get(SomeService::class));
        return new Response;
    }
}

输出:

bool(false)

为什么我注册了两项服务而不是一项?

那是因为您在 services.yaml.

中注册了两次

此行自动执行一次:

App\:
    resource: '../src/*'
    exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'

另一个,手动:

someservice:
    class: App\Service\SomeService

因为它们有不同的名称(someserviceApp\Service\SomeService),它们在 Symfony 中是不同的。

我建议您删除第二个声明,并在您的控制器中只调用具有完全限定名称的服务:$this->get(SomeService::class)