@@ -77,12 +77,33 @@ 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;
80
+ use function Symfony\Component\DependencyInjection\Loader\Configurator\service_closure;
82
81
83
82
return function (ContainerConfigurator $configurator) {
84
83
$services = $configurator->services();
85
84
86
85
$services->set(MyService::class)
87
- ->args([new ServiceClosureArgument(new Reference('mailer'))]);
86
+ ->args([service_closure('mailer')]);
87
+
88
+ // In case the dependency is optional
89
+ // $services->set(MyService::class)
90
+ // ->args([service_closure('mailer')->nullOnInvalid()]);
88
91
};
92
+
93
+ Using Service Closures in Compiler Passes
94
+ -----------------------------------------
95
+
96
+ In :doc: `compiler passes </service_container/compiler_passes >` you can create
97
+ a service closure by wrapping the service reference into an instance of
98
+ :class: `Symfony\\ Component\\ DependencyInjection\\ Argument\\ ServiceClosureArgument `::
99
+
100
+ use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
101
+ use Symfony\Component\DependencyInjection\ContainerBuilder;
102
+ use Symfony\Component\DependencyInjection\Reference;
103
+
104
+ public function process(ContainerBuilder $container): void
105
+ {
106
+ // ...
107
+
108
+ $myService->addArgument(new ServiceClosureArgument(new Reference('mailer')));
109
+ }
0 commit comments