Warning: You are browsing the documentation for Symfony 4.0, which is no longer maintained.
Read the updated version of this page for Symfony 6.0 (the current stable version).
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
in your service definition:
1 2 3 4 5
# config/services.yaml services: App\SomeNonSharedService: shared: false # ...
1 2 3 4
<!-- config/services.xml --> <services> <service id="App\SomeNonSharedService" shared="false" /> </services>
1 2 3 4 5
// config/services.php use App\SomeNonSharedService; $container->register(SomeNonSharedService::class) ->setShared(false);
Now, whenever you request the
App\SomeNonSharedService from the container,
you will be passed a new instance.