How to implement dependency injection with custom blocks in Drupal 8

At this point into the Drupal 8 life cycle, I’ve seen enough code by developers formerly coding in Drupal 7 neglecting to utilize Symfony’s dependency injection mechanism.  This is a short demonstration on how to inject services into a custom block.

For this example I’ll use code from a live commerce project for a trading card marketplace.  On the back-end of the site, a marketplace seller (store) has a portal with a dashboard and various options to manage their inventory and track sales data.  Information required for the portal is handled by a store service.  This screenshot is from a test account that shows what data the store service provides for a particular row of data boxes in the dashboard:


Dependency injection example blocks


The custom block code to render this row of data boxes:



Implementing the ContainerFactoryPluginInterface and Symfony's ContainerInterface classes are the components required to inject services into your block plugin.