Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version

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
    2
    3
    4
    5
    # app/config/services.yml
    services:
        AppBundle\SomeNonSharedService:
            shared: false
            # ...
    
  • XML
    1
    2
    3
    4
    <!-- app/config/services.xml -->
    <services>
        <service id="AppBundle\SomeNonSharedService" shared="false"/>
    </services>
    
  • PHP
    1
    2
    3
    4
    5
    // app/config/services.php
    use AppBundle\SomeNonSharedService;
    
    $container->register(SomeNonSharedService::class)
        ->setShared(false);
    

Now, whenever you request the AppBundle\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.