How to Define Non Shared Services

How to Define Non Shared Services

In the service container, all services are shared by default. This means that each time you retrieve the service, you’ll get the same instance. This is usually the behavior you want, but in some cases, you might want to always get a new instance.

In order to always get a new instance, set the shared setting to false in your service definition:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\SomeNonSharedService:
    4. shared: false
    5. # ...
  • XML

    1. <!-- config/services.xml -->
    2. <services>
    3. <service id="App\SomeNonSharedService" shared="false"/>
    4. </services>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\SomeNonSharedService;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set(SomeNonSharedService::class)
    7. ->share(false);
    8. };

Now, whenever you request the App\SomeNonSharedService from the container, you will be passed a new instance.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.