2 Methods to Exclude Service From Container in Symfony 7

2 Methods to Exclude Service From Container in Symfony 7

Symfony provides a powerful dependency injection system that allows developers to manage and organize services within their applications seamlessly. While the dependency injection container is a key component for managing services, there might be scenarios where you need to exclude a specific service from being instantiated in the container. This tutorial provides 2 methods how to exclude service from container in Symfony 7.

Method 1 - 'exclude' option

In the provided Symfony configuration snippet, the services.yaml file is configured to autoload services from the App namespace located in the ../src/ directory. The TestService is marked for exclusion using the exclude option. This means that Symfony will skip registering TestService as a service during the container building process.

config/services.yaml

services:
    # ...

    App\:
        resource: '../src/'
        exclude:
            # ...
            - '../src/Service/TestService.php'

We can utilize the following command to verify whether a service has been included in the container or not:

php bin/console debug:container App\Service\TestService

Output:

 ---------------- --------------------------------------------------------
  Option           Value
 ---------------- --------------------------------------------------------
  Service ID       App\Service\TestService
  Class            App\Service\TestService
  Tags             container.excluded (source: in "config/services.yaml")
  Public           no
  Synthetic        no
  Lazy             no
  Shared           yes
  Abstract         yes
  Autowired        no
  Autoconfigured   no
  Usages           none
 ---------------- --------------------------------------------------------

Method 2 - 'Exclude' attribute

We can exclude a specific service from the container by employing the #[Exclude] attribute.

src/Service/TestService.php

<?php

namespace App\Service;

use Symfony\Component\DependencyInjection\Attribute\Exclude;

#[Exclude]
class TestService
{
}

Leave a Comment

Cancel reply

Your email address will not be published.