Showing results for 
Search instead for 
Did you mean: 

Use a generated factory with virtual types?

Use a generated factory with virtual types?


When defining a virtual type in di.xml, it seems that you can't use the associated Factory in dependency injection afterwards.

For example with the following definition (just here as an example, using factory with sessions is meaningless):


#File: app/code/Magento/Catalog/etc/di.xml 
<virtualType name="Magento\Catalog\Model\Session\Storage" type="Magento\Framework\Session\Storage">
        <argument name="namespace" xsi:type="string">catalog</argument>


Attempting to inject a factory for that virtual type in a constructor

class MyClass {
    public function __construct(
        Magento\Catalog\Model\Session\StorageFactory $storageFactory
    ) {

results in the following error message at runtime:
Class Magento\Catalog\Model\Session\StorageFactory does not exist

(I also stumbled upon another message in a similar situation:
Source class "\Magento\Catalog\Model\Session\Storage" for "Magento\Catalog\Model\Session\StorageFactory" generation does not exist.)


If it's the desired behaviour, what's the solution to create new instances of a virtual type at runtime?




(original question on Github: