@@ -77,16 +77,36 @@ argument of type ``service_closure``:
77
77
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
78
78
79
79
use App\Service\MyService;
80
- use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
81
- use Symfony\Component\DependencyInjection\Reference;
82
80
83
81
return function (ContainerConfigurator $configurator) {
84
82
$services = $configurator->services();
85
83
86
84
$services->set(MyService::class)
87
- ->args([new ServiceClosureArgument(new Reference('mailer'))]);
85
+ ->args([service_closure('mailer')]);
86
+
87
+ // In case the dependency is optional
88
+ // $services->set(MyService::class)
89
+ // ->args([service_closure('mailer')->ignoreOnInvalid()]);
88
90
};
89
91
90
92
.. seealso ::
91
93
92
94
Another way to inject services lazily is via a :doc: `service locators </service_container/service_subscribers_locators >`.
95
+
96
+ Using Service Closures in Compiler Passes
97
+ -----------------------------------------
98
+
99
+ In :doc: `compiler passes </service_container/compiler_passes >` you can create
100
+ a service closure by wrapping the service reference into an instance of
101
+ :class: `Symfony\\ Component\\ DependencyInjection\\ Argument\\ ServiceClosureArgument `::
102
+
103
+ use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
104
+ use Symfony\Component\DependencyInjection\ContainerBuilder;
105
+ use Symfony\Component\DependencyInjection\Reference;
106
+
107
+ public function process(ContainerBuilder $container): void
108
+ {
109
+ // ...
110
+
111
+ $myService->addArgument(new ServiceClosureArgument(new Reference('mailer')));
112
+ }
0 commit comments