Autowiring services created with factory

248 views Asked by At

According to the official documentation, Autowiring allows you to manage services in the container with minimal configuration. It reads the type-hints on your constructor (or other methods) and automatically passes the correct services to each method.

So in order to have the service, the container must search for the ID that corresponds to the type-hint.

So, this are, the following interface & classes in my example

interface ServiceInterface
{
  public function doSomThing(): void;
}


class Service1 implements ServiceInterface {
     
      public function doSomThing(): void
      {
          echo "service1";
      }
}

class Service2 implements ServiceInterface {
     
        public function doSomThing(): void
        {
          echo "service2";
        }
}


class Service3 implements ServiceInterface {

     public function doSomThing(): void
     {
          echo "service3";
     }
}

//service.yml
DEL\Bundle\CoreBundle\Service\Base\Service1: ~ 

DEL\Bundle\CoreBundle\Service\Base\Service2:  ~

DEL\Bundle\CoreBundle\Service\Base\Service3:  ~

And finally, this is the factory service that creates a set of classes that implement the interface ServiceInterface.

//service.yml
DEL\Bundle\CoreBundle\Service\Base\ServiceInterface:
    autowire: false
    factory: ['@delcore.factory.service', serviceChoice]


class ServiceFactory {

    public function serviceChoice(string $param): ServiceInterface
    {
       switch ($param) {
           case 'label1':
              return new Service1();
           break;
            case 'label2':
             return new Service2();
            break;
            case 'label3':
             return new Service3();
            break;

    } 
}

The problem is that the method returns an object that implements ServiceInterface which cannot be found by container through "autowiring".

What can I do? knowing that you don't want to remove the factory entry from the service.interface configuration.

0

There are 0 answers