Symfony create new service as a new instance

Viewed 2556

I have a service defined with several dependency injections in the constructor. At some point I want to get the service as a new instance instead of the same instance already created. Note that normally I want the service to be shared, but on an edge case I want to create a new instance, so the shared option in the service definition is not aplicable.

I can create a new object, but I then I would have to inject the dependencies manually, and I would prefer to let symfony to deal with it.

So how can I tell Symfony to return a service as a new instance?

Thank you.

1 Answers

As far as I know, there is no way to tell the Symfony Dependency Injection Container to return some times the shared instance, and other times a new instance of a service.

By default, the services are shared, as you already found out. You can tell the container to create a not-shared service by setting the shared setting to false in your service definition:

# app/config/services.yml
services:
    AppBundle\SomeNonSharedService:
        shared: false

Armed with this knowledge, I think the solution for your issue is to create a duplicate of the shared service with a different name and mark it as not-shared as explained above. When you ask the container to get the duplicate, it will create a new instance every time.

Do not attempt to create the duplicate as an alias of the original service, it doesn't work. The first thing the implementation of Contaner::get() does is to search for the service ID provided as argument into the list of aliases and use the ID of the original service instead if it finds it there.

Related