Documentation

How to Inject Instances into the Container

How to Inject Instances into the Container

Register synthetic services when instances are created outside the container.

In some applications, you may need to inject a class instance as service, instead of configuring the container to create a new instance.

YAML
services:
    # synthetic services don't specify a class
    app.synthetic_service:
        synthetic: true
JS
let definition = container.register('app.synthetic_service')
definition.synthetic = true

Now, you can inject the instance in the container using container.set() method:

let instantiatedService = ...;
container.set('app.synthetic_service', instantiatedService);