Multiple services of type

Ajax
Member | 57
+
+1
-

Hello!

I have class \App\Model\Files\File

class File extends Nette\Object
{
    ....
}

And I have class \App\Model\Files\XmlFile

class XmlFile extends File
{
    ...
}

Another service need to work with \App\Model\Files\File, so I did this:

class SystemState extends Nette\Object
{
    public function __construct(\App\Model\Files\File $stateFile) {
        $this->stateFile = $stateFile;
    }
}

and in presenter:

/** @var \App\Model\SystemState @inject */
public $sysState;

config.neon:

`Services
App\Model\Files\File
App\Model\Files\XmlFile

`

Problem is, that Tracy is not happy:

Service '28_App_Model_SystemState': Multiple services of type App\Model\Files\File found: 24_App_Model_Files_XmlFile, 25_App_Model_Files_File
`

I'm little bit lost in DI, can comeone point me to right direction? THANKS!

lutor
Member | 27
+
+3
-

Hi,
it is because you have defined two services, that are (subclasses) of class App\Model\Files\File – App\Model\Files\File itself and App\Model\Files\XmlFile (which extends App\Model\Files\File), so DI container does not know, which one of them inject into SystemState constructor.

Solution would be turning off autowiring on one of these services (DI will use service that is autowired) or specifying name of service, you want to inject to SystemState service.

So in your config.neon will look like this:

services:
    fileService: \App\Model\Files\File
    systemState: \App\Model\SystemState(@fileService)

Comments

Ajax:

Great! Thanks!!

5 years ago