drupal 9 custom blocks dependency injection

Drupal 9 Custom Blocks Dependency Injection

To implement dependency injection in custom blocks in Drupal 9, you can follow these steps:

  1. Create a custom block class that extends the BlockBase class.
  2. Define the dependencies for your block in the constructor of the custom block class.
  3. Use the dependency injection container to inject the dependencies into the block class.

Here's an example of how you can implement dependency injection in a custom block in Drupal 9:


namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

 * Provides a custom block.
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My Custom Block"),
 * )
class MyCustomBlock extends BlockBase implements ContainerFactoryPluginInterface {

   * The dependency.
   * @var \Drupal\my_module\MyDependency
  protected $myDependency;

   * Constructs a new MyCustomBlock instance.
   * @param array $configuration
   *   The block configuration.
   * @param string $plugin_id
   *   The plugin ID for the block.
   * @param mixed $plugin_definition
   *   The plugin definition for the block.
   * @param \Drupal\my_module\MyDependency $my_dependency
   *   The dependency.
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MyDependency $my_dependency) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->myDependency = $my_dependency;

   * {@inheritdoc}
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(

   * {@inheritdoc}
  public function build() {
    // Use the injected dependency in your block logic.
    $dependencyResult = $this->myDependency->doSomething();

    // Build the block output.
    $build = [
      '#markup' => $this->t('Dependency result: @result', ['@result' => $dependencyResult]),

    return $build;


In this example, the MyCustomBlock class extends the BlockBase class and implements the ContainerFactoryPluginInterface. The constructor of the MyCustomBlock class accepts the MyDependency class as a dependency. The create() method is used to create an instance of the block and inject the dependency using the dependency injection container.

You will need to replace my_module with the actual name of your module and MyDependency with the actual name of your dependency class.

Note: This example assumes that you have already created a custom module and defined the MyDependency class.