dependency injection – Return a Closure from a Factory

I have services that depend on request information. I’m trying to create a Factory Factory which will have the Dependency Injection container returns a factory (an anonymous function) that will create the services I want. So basically somthing like this:

class FooFactoryFactory {
  public static function create(ContainerInterface $container): callable {
     return static function (Request $request) use ($container) {
       $raz = request->get('param_raz');
       return new Bar(


The issue I have is that the Closure is properly created, but de Drupal’s Dependency Injection Container class tries to set a proprty to the Closure. This cannot work and ends in a fatal error:

Closure object cannot have properties

Here is the place where it occurs:

// DrupalComponentDependencyInjection/Container::createService() - Line 283-293
if (isset($definition('properties'))) {
  if ($definition('properties') instanceof stdClass) {
    $definition('properties') = $this->resolveServicesAndParameters($definition('properties'));
  foreach ($definition('properties') as $key => $value) {
    if(!$service instanceof Closure){
      $service->{$key} = $value;  // <-- Will not work for Closure

So the questions I have:

  • Is this by design? Meaning is it something thta is not wanted in term of coding practice?
  • The error can be avoided if I manage to make sure, that the service I want to create does not have properties it it’s definition. I just don’t know how to achieve this.

Thanks for the help on this matter.