Dependency Injection in Magento 2 looks like magic at first. You type an interface in the constructor and Magento delivers the right implementation. How does it know what to inject? How does DI compilation work? What are virtual types and what are they for? I break it all down.
Basics – what is a DI container
A DI container builds objects for you – along with all their dependencies. Instead of writing:
<?php
// Without DI - manual dependency creation
$logger = new \Monolog\Logger('app');
$repository = new ProductRepository($logger, new DbConnection());
$service = new ProductService($repository, $logger);
You ask the container for an object and it resolves the entire dependency tree:
<?php // With DI - container resolves the whole tree $service = $objectManager->get(ProductService::class);
In Magento 2 never use ObjectManager directly in your own code (except in Factory and Proxy). Declare dependencies in the constructor; Magento injects them automatically.
How Magento resolves types – di.xml and compilation
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!-- When someone asks for ProductRepositoryInterface, give them ProductRepository -->
<preference for="Magento\Catalog\Api\ProductRepositoryInterface"
type="Magento\Catalog\Model\ProductRepository"/>
</config>
During compilation (bin/magento setup:di:compile) Magento analyses all di.xml files, builds the complete dependency graph and generates Interceptor classes (for plugins) and Proxy classes into generated/. That is why you need to recompile after changing di.xml – in developer mode Magento does this automatically.
Constructor arguments – injecting concrete values
<config>
<type name="Vendor\Module\Model\ApiClient">
<arguments>
<argument name="timeout" xsi:type="number">30</argument>
<argument name="baseUrl" xsi:type="string">https://api.example.com</argument>
<argument name="logger" xsi:type="object">Psr\Log\LoggerInterface</argument>
</arguments>
</type>
</config>
Virtual Types – classes without writing PHP
Virtual Type is one of the most underrated Magento 2 mechanisms. It creates a “new class” through XML configuration – without a single line of PHP. Useful when you want two instances of the same class with different parameters:
<config>
<virtualType name="Vendor\Module\Model\FileLogger"
type="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="name" xsi:type="string">file_logger</argument>
</arguments>
</virtualType>
<virtualType name="Vendor\Module\Model\ApiLogger"
type="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="name" xsi:type="string">api_logger</argument>
</arguments>
</virtualType>
<type name="Vendor\Module\Model\ApiClient">
<arguments>
<argument name="logger" xsi:type="object">Vendor\Module\Model\ApiLogger</argument>
</arguments>
</type>
</config>
Virtual Types exist only in the DI container – you cannot use them as PHP type hints. But you can inject them as arguments via xsi:type="object".
Shared vs Non-shared – singleton or new object?
By default Magento creates each class as a singleton within a single request. When you need multiple instances of the same class, Magento auto-generates a Factory class:
<?php
class OrderProcessor
{
public function __construct(
private \Vendor\Module\Model\OrderFactory $orderFactory
) {}
public function processMany(array $orderData): void
{
foreach ($orderData as $data) {
// Each create() returns a fresh Order instance
$order = $this->orderFactory->create(['data' => $data]);
$order->process();
}
}
}
Summary
Preference maps interfaces to implementations, Virtual Types let you configure class variants without PHP, Factory is the solution when you need multiple instances of one class. Understand these three and Magento DI becomes predictable.
